When I'm using Postman,
Putting values from raw works perfectly.
But in Android, I am receiving Error Code 415.
REVIEW_URL = "http://somesite.esy.es/api.php/registration";
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest request = new StringRequest(Request.Method.POST, REVIEW_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("RESPONSE:", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ERROR",""+error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String,String>();
params.put("device_id", "11111");
return params;
}
#Override
public String getBodyContentType() {
return "application/raw";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String,String>();
params.put("Content-Type", "application/raw");
return params;
}
};
requestQueue.add(request);
Am I doing it right chaging content type to raw? thanks.
your content type is not supported, so I suggest changing it to
"application/json"
this worked for me.
as shown here, this is the correct one.
thanks, hope it helps.
JsonObjectRequest use this Volly Object is right.
Related
I am trying to retrieve a response from my server in my Android App but getting "com.android.volley.ServerError"
E/Volley: [224669] BasicNetwork.performRequest: Unexpected response code 400 for http://52.74.115.250:8080/api/products
When I try in Postman,I do get a response.
This is my code for GET request:
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, Constants.productListUrlStr, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("jsonsucces","success");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("jsonerror",error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", Constants.getToken(getActivity()));
//headers=globalProvider.addHeaderToken(getActivity());
return headers;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
if (contract!=null){
if(contract._supplier!=null){
Log.d("checksupplier",contract._supplier);
params.put("_supplier",contract._supplier);
}
}
if(!globalProvider.ShangpingHeaderLoadCategory .equals("")){
params.put("category",globalProvider.ShangpingHeaderLoadCategory);
Log.d("checkcategoryhe",globalProvider.ShangpingHeaderLoadCategory);
}
return params;
}
};
globalProvider.addRequest(jsonObjectRequest);
what am I doing wrong?
There are few posts about getParams() not working anymore for JsonObjectRequest volley request.
Alternatively either you can use StringRequest or do a little tweak in your request as below
JSONObject jOb = new JSONObject();
try {
jOb.put("_supplier", contract._supplier);
jOb.put("category", globalProvider.ShangpingHeaderLoadCategory);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, Constants.productListUrlStr, jOb, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("jsonsucces","success");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("jsonerror",error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", Constants.getToken(getActivity()));
//headers=globalProvider.addHeaderToken(getActivity());
return headers;
}
};
I figured out,Since I am passing query parameter I was constructing my url incorrectly.
String uri= String.format(Constants.productListUrlStr+"?_supplier=%1$s",contract._supplier);
StringRequest stringRequest=new StringRequest(Request.Method.GET, uri, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("checksuc",response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("checkstrerr",error.networkResponse.headers.toString());
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", Constants.getToken(getActivity()));
//headers=globalProvider.addHeaderToken(getActivity());
return headers;
}
}
;
globalProvider.addRequest(stringRequest);
I am working with oauth2 and using Volley networking library in android. I am trying to get access token by using below code. But I getting 400 Bad request as my response. What is wrong in my request ? I even tried putting content type as application/x-www-form-urlencoded but still no luck. What can be the main cause for error ?
StringRequest accessTokenRequest = new StringRequest(Request.Method.POST, oauthConfig.getTokenEndPointUrl(), new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Log.e("AccessTokenFromLogin", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put(OAuthConstants.GRANT_TYPE, "password");
params.put(OAuthConstants.USERNAME, userEmail);
params.put(OAuthConstants.PASSWORD, userPassword);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", "application/x-www-form-urlencoded");
if (isValid(clientId))
params.put(OAuthConstants.CLIENT_ID, clientId);
if (isValid(clientSecret))
params.put(OAuthConstants.CLIENT_SECRET, clientSecret);
if (isValid(scope))
params.put(OAuthConstants.SCOPE, scope);
Log.e("LoginActivity",clientId+" "+clientSecret+" "+scope);
return params;
}
};
Volley.newRequestQueue(this, hurlStack).add(accessTokenRequest);
I'm trying to use KairosAPI's enroll POST request using Android Volley. However I keep getting Error 1002, image one or more required parameters are missing. I've tried two ways to add the parameters into the body of the JSON, which I've outlined in the code.
This is my code-
public class MainActivity extends AppCompatActivity {
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
postRequestToEnrollPersonInGallery();
}
public void postRequestToEnrollPersonInGallery() {
final String appId = "3e12****";
final String appKey = "156e06fd782a3304f085f***********";
String mainUrl = "https://api.kairos.com/";
String enrollRequestUrl = "enroll";
requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, mainUrl + enrollRequestUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Volley", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", "application/json");
params.put("app_id", appId);
params.put("app_key", appKey);
return params;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("image", "https://s-media-cache-ak0.pinimg.com/originals/c6/c0/04/c6c004ec669d92faa36d8ff447884293.jpg");
params.put("subject_id", "12345");
params.put("gallery_name", "FirstGallery");
/*params.put("image", "\"url\":\"https://s-media-cache-ak0.pinimg.com/originals/c6/c0/04/c6c004ec669d92faa36d8ff447884293.jpg\"");
params.put("subject_id", "\"subject_id\":\"12345\"");
params.put("gallery_name", "\"gallery_name\":\"FirstGallery\""); -- i tried this too*/
return params;
}
};
requestQueue.add(stringRequest);
}
}
You aren't posting JSON.
You can either
1) Learn to use JsonObjectRequest
final JSONObject body = new JSONObject();
body.put(... , ...);
Request request = new JsonObjectRequest(url, body, ...);
2) Actually post a JSON String.
StringRequest request = new StringRequest(...) {
#Override
public byte[] getBody() throws AuthFailureError {
JSONObject params = new JSONObject();
params.put("image", "https://s-media-cache-ak0.pinimg.com/originals/c6/c0/04/c6c004ec669d92faa36d8ff447884293.jpg");
params.put("subject_id", "12345");
params.put("gallery_name", "FirstGallery");
return params.toString().getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
I have tried every single method available on stackoverflow but result remains the same.
I want to send params and also api key in the Authorization field of header using volley.
Here is the code snippet.
holder.comment_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String POSTCOMMENT_URL = Utility.getIPADDRESS()+"comments";
volleySingleton = VolleySingleton.getInstance();
requestQueue = volleySingleton.getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, POSTCOMMENT_URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("Response: " , response.toString());
Toast.makeText(myApplication.getApplicationContext(),response.toString(),Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(myApplication.getApplicationContext(),"Error", Toast.LENGTH_LONG).show();
}
}){
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Authorization", getApiKey() );
return params;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("pid", "39");
params.put("comment", "mobile testing");
return params;
}
};
requestQueue.add(jsonObjectRequest);
}
});
I'm getting this error:
[5333] BasicNetwork.performRequest: Unexpected response code 400 for http://www.XXXXXXXXXXX.com/comments
I have already tested the endpoint using Advanced Rest client, it works and returns the JsonObject with previously added comment.
Here are the results:
{
"error": false
"message": "comment added successfully added!"
"comment_id": "12"
"user_id": "12"
"pid": "39"
"comment": "testing for stackoverflow"
"date of comment": "2016-07-30 13:49:08"
}
Ok, after a long research and stupid rather valuable changes, it finally worked for me.
Here is the working code:
holder.comment_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
final String api_key = getApiKey();
String POSTCOMMENT_URL = Utility.getIPADDRESS()+"comments";
volleySingleton = VolleySingleton.getInstance();
requestQueue = volleySingleton.getRequestQueue();
StringRequest stringRequest = new StringRequest(Request.Method.POST, POSTCOMMENT_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(myApplication.getApplicationContext(),response,Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(myApplication.getApplicationContext(),error.toString(),Toast.LENGTH_LONG).show();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Authorization", api_key);
return params;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("pid", "40");
params.put("comment", "testing");
return params;
}
};
requestQueue.add(stringRequest);
}
});
Note: It worked for me, I'm not sure about others.
Changes are: Change JsonObjectRequest to StringRequest and removing any Content-Type doesn't make any difference, so I removed it.
Also, make sure all the params have some values i.e test it by logging.
I'm trying to use Volley library to communicate with my RESTful API.
I have to POST string in the body, when I'm asking for the bearer Token. String should look like this:
grant_type=password&username=Alice&password=password123
And header:
Content-Type: application/x-www-form-urlencoded
More info about WebApi Individual Accounts:
http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api
Unfortunately I can't figure out how can I solve it..
I'm trying something like this:
StringRequest req = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.v("Response:%n %s", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", "User0");
params.put("password", "Password0");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
return headers;
}
};
I'm getting 400 Bad Request all the time.
I think that I'm actually sending request like this:
grant_type:password, username:User0, password:Password0
instead of:
grant_type=password&username=Alice&password=password123
I would be very grateful if anyone has any ideas or an advice..
To send a normal POST request (no JSON) with parameters like username and password, you'd usually override getParams() and pass a Map of parameters:
public void HttpPOSTRequestWithParameters() {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://www.somewebsite.com/login.asp";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR","error => "+error.toString());
}
}
) {
// this is the relevant method
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
// volley will escape this for you
params.put("randomFieldFilledWithAwkwardCharacters", "{{%stuffToBe Escaped/");
params.put("username", "Alice");
params.put("password", "password123");
return params;
}
};
queue.add(postRequest);
}
And to send an arbitary string as POST body data in a Volley StringRequest, you override getBody()
public void HttpPOSTRequestWithArbitaryStringBody() {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://www.somewebsite.com/login.asp";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR","error => "+error.toString());
}
}
) {
// this is the relevant method
#Override
public byte[] getBody() throws AuthFailureError {
String httpPostBody="grant_type=password&username=Alice&password=password123";
// usually you'd have a field with some values you'd want to escape, you need to do it yourself if overriding getBody. here's how you do it
try {
httpPostBody=httpPostBody+"&randomFieldFilledWithAwkwardCharacters="+URLEncoder.encode("{{%stuffToBe Escaped/","UTF-8");
} catch (UnsupportedEncodingException exception) {
Log.e("ERROR", "exception", exception);
// return null and don't pass any POST string if you encounter encoding error
return null;
}
return httpPostBody.getBytes();
}
};
queue.add(postRequest);
}
As an aside, Volley documentation is non-existent and quality of StackOverflow answers is pretty bad. Can't believe an answer with an example like this wasn't here already.
First thing, I advise you to see exactly what you're sending by either printing to the log or using a network sniffer like wireshark or fiddler.
How about trying to put the params in the body? If you still want a StringRequest you'll need to extend it and override the getBody() method (similarly to JsonObjectRequest)
I know this is old, but I ran into this same problem and there is a much cleaner solution imo found here: How to send a POST request using volley with string body?