Volley Post method gives me unexpected response code 400? - android

Here am new for android development am trying to post json value to server using gson lib i have converted into json but when i try to send to server is throws 400 unexpected response code here let me post my code:
listobj = account_sf_db.toServer();
Gson gson = new Gson();
RequestQueue queue = Volley.newRequestQueue(getBaseContext());
final String yog = gson.toJson(listobj);
String URL = "http://xxx.xx.xx.xxx/xxx/CRM/AcoountCreatePageLoad.svc/xxt/xxxt/ " +yog ;
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String resp = response.toString();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("god", yog);
return params;
} #Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Accept","application/json");
headers.put("User-agent", "My useragent");
return headers;
}
};
queue.add(stringRequest);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}

400 status code is for Bad Request, it means server is not expecting this type of request.
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
Please check headers(content-type, user agent,etc.) you are adding whether it is required or not. It might happen that server is expecting a simple request and not json request.
Also try to read out error you get in onErrorResponse. Server might have responded you the expected parameter and request type, and also discuss the type of API developed by the web developer.

You have a space in your url after the /xxt/xxxt/
String URL = "http://xxx.xx.xx.xxx/xxx/CRM/AcoountCreatePageLoad.svc/xxt/xxxt/ " +yog ;
Remove it and I think you'll be fine.
P.S 400 generally means there is something wrong with the Url or parameters.

Related

Can't add Volley parameter

I can't get it done...
I need to download json with Volley library, and I need to put inside header and body in POST parameter:
usr = "example#ciao.com";
pwd = "123Prova!";
String url = "http://localhost:8080/...";
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i("VOLLEY", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
Toast.makeText(MainActivity.this, "qualche errore", Toast.LENGTH_LONG).show();
}
}){
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", "application/json; charset=utf-8");
params.put("wellu-client-id", "a056fe5c-1dac-4c12-8b57-8189e45c0b58");
return params;
}
#Override
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("email", usr);
params.put("password", pwd);
return params;
}
};
Volley.newRequestQueue(getApplicationContext()).add(jsonRequest);
this parameter work in Postman chrome app... but here brings me in .ErrorListener() and I really don't know why.
You should put the address (IP) of your server not localhost (localhost in an android device is itself, not the server)
String url = "http://localhost:8080/...";
So change the localhost part to the ip address of your server and make sure the server and the android device are connected to the same network.
Alternatively overriding the function
public byte[] getBody() to send data.But you must be change your backend codes

Android Volley request failing

I am attempting a Volley request through android to get Oauth credentials using a password grant type. What I am trying works in postman, but is not working in android and I am not sure what I am doing wrong. Below please find the code I am using:
final RequestQueue queue = Volley.newRequestQueue(this);
final String url = Constants.OAUTH_URL;
Map<String, String> body = new HashMap<>();
body.put("grant", "password");
final JSONObject jso = new JSONObject(body);
JsonObjectRequest postRequest = new JsonObjectRequest (Request.Method.POST, url, jso,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(final JSONObject response) {
//Do something
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
responseText.setText(error.toString());
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("accept", "application/vnd.TestKitchen.v1+json");
headers.put("Authorization", BasicAuth.getBasicAuth(Constants.USERNAME, Constants.PASSWORD));
headers.put("Content-Type", "application/json; charset=UTF-8");
return headers;
}
};
queue.add(postRequest);
My OAuth URL is correct, I have verified that several times. So the problem isn't a typo on that end. All of the other fields should still reach my server and give an appropriate response (Be it an error or not), however all requests I send are returning with a 400 response. Anything obvious I am doing wrong that I should fix? Any help is appreciated. Thanks.
Why are you using this thing?
Map<String, String> body = new HashMap<>();
body.put("grant", "password");
final JSONObject jso = new JSONObject(body);
You can directly put the value in JSONObject
JSONObject jso = new JSONObject();
jso.put("grant", "password");
In the case of a REST API with a JSON payload, 400's are typically, and correctly I would say, used to indicate that the JSON is invalid in some way according to the API specification for the service.

how NOT to escape slashes, sending POST request using volley

I am sending POST request using volley. Request has custom headers and json request body. One of the json values in request body is a URL. When i create a jsonobject the // in URL is sent as \/\/. (e.g. "key1:"http//www.xyz.com" is sent as "key1":"http:\/\/www.xyz.com"
This causes a 400 error. How do i fix this?
Here is the POST using volley:
RequestQueue queue = Volley.newRequestQueue(this);
try{
jsonBody = new JSONObject();
jsonBody.put("Key1","http://xyz1.com");
jsonBody.put("Key2","val2");
}
catch (JSONException e){
}
JsonObjectRequest req = new JsonObjectRequest(Request.Method.POST,URL, jsonBody,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// handle response
Log.d("MAIN","response recd="+response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// handle error
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("CUSTOM_HEADER", "Yahoo");
headers.put("ANOTHER_CUSTOM_HEADER", "Google");
return headers;
}
};
queue.add(req);
The json values were correctly formatted. Checked by priting jsonbody.get("key")
the slashes are escaped when printing out the json using .toString.
For my case, the 400 error was fixed by adding header:
params.put("Content-Type","application/json; charset=utf-8");

How to send POST request in JSON and response in JSON using volley (Android)

private void login(){
// Post params to be sent to the server
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", username);
params.put("password", password);
JsonObjectRequest req = new JsonObjectRequest(login_URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.v("Response:%n %s", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
}){
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
// add the request object to the queue to be executed
AppController.getInstance().addToRequestQueue(req);}
I got below error:
E/Volley: [1] 10.onErrorResponse: Error:
i dont know where the problem
json send as post:
{
"":"",
"":"",
"":"",
}
json response as:
{"":""}
You should add the Request.Method.POST as the first parameter of your new JsonObjectRequest method. Also scrap out the new 'JSONObject(params)'.
Now override the getParams() method just above your getParams override and add the content of your login method there. You should return params.
It should work. Let me know if you have any challenges. :).
A very good example would be here
Volley library can be integrated using grader and if you want to know about implementation of Requests in volley then following link can give you all types of requests you can make with volley and how to implement it .
Here you go
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

Put request using volley

I am trying to update data on server by using PUT method but I am getting this error , I haven't used volley before ,Is there anything I am missing ? please suggest .
My code :
private void sendRequest() {
RequestQueue queue = Volley.newRequestQueue(getActivity());
PersonalInfoModel.Data.PersonalInformation.Address address;
address = new PersonalInfoModel().new Data().new PersonalInformation().new Address();
address.setBuilding("test");
address.setCountry("test");
address.setCounty("test");
address.setPostcodeInCode("");
address.setPostcodeOutCode("");
address.setTown("");
PersonalInfoModel.Data.PersonalInformation data;
data = new PersonalInfoModel().new Data().new PersonalInformation();
data.setDob("tsst");
data.setEmail("testemai");
data.setForename("test");
data.setSurname("data");
data.setAddress(address);
Gson gson = new Gson();
JSONString = gson.toJson(data);
try {
obj = new JSONObject(JSONString);
} catch (JSONException e) {
e.printStackTrace();
}
LogUtils.LOGD(TAG, "JSONString is :: " + JSONString.toString());
JsonObjectRequest putRequest = new JsonObjectRequest(Request.Method.PUT, urlUserDetail, obj,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
// response
LogUtils.LOGD("Response", response.toString());
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
LogUtils.LOGD("Error.Response", error.toString());
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("tess", "2222");
params.put("Authorization", "def1bc98d032");
params.put("Content-Type", "application/json; charset=utf-8");
return params;
}
#Override
public byte[] getBody() {
try {
LogUtils.LOGD("json", obj.toString());
return obj.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
};
queue.add(putRequest);
}
Error :
BasicNetwork.performRequest: Unexpected response code 400 for url
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("tess", "2222");
params.put("Authorization", "def1bc98d032");
// add this parameter
params.put("Content-Type", "application/json; charset=utf-8");
return params;
}
Check with PostMan or some client and check if you are getting a right response back and eliminate that possibility - the request works without using android volley
Response code 400 means Bad request. It means that the request you're making is incorrect. Possibly the content type has an error, try adding
params.put("Content-Type", "application/json; charset=utf-8"); to getHeaders()
try removing the getbody method.. because you are sending the request parameters as a json object and content type header is also application/json.so getbody won't be necessary
JsonObjectRequest adds Content-Type: application/json; charset=utf-8 by default. Your params.put("Content-Type", "application/json; charset=utf-8"); adds another Content-Type and some applications don't work with multiple Content-Type definitions. You should try to remove params.put("Content-Type", "application/json; charset=utf-8");.
Make sure that the request URL for a PUT request has the id of the resource as the last path segment. Otherwise you will get a 404.
Wrong form of URL:
/users
Correct form of URL:
/users/bob

Categories

Resources