Put request using volley - android

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

Related

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/

Volley Post method gives me unexpected response code 400?

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.

Volley post method return response code 500

Always i get below error response when using volley
06-24 15:06:59.244: E/Volley(12869): [2311] BasicNetwork.performRequest: Unexpected response code 500 for http://My_API
my code for Volley call
String sSignupUrl = STController.getInstance()
.getResourceManager(LoginActivity.this)
.getServerPropertyValue(URLConstants.API_LOGIN);
JSONObject params = new JSONObject();
try {
params.put("username", "usernam");
params.put("passwd", "password");
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
sSignupUrl, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
LogUtil.d("TAG" + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "Error: " + error.getMessage());
}
}) {
#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;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
I can successfully get the response when using URLConnection manager, not able to find the error, i have search through google but dint get proper solution, all answers are most welcome
Thanks in advance
I did have the same situation. What i have done wrong is that i included getHeaders() in wrong JsonObjectRequest(i.e. with a wrong url). But I used a custom header in my situation. Check your url. It may not be the correct one. It may not accepting this header.

Passing Parameters into Android Volley POST Request, return JSON

I am attempting a Volley POST request that passes in the parameter friends_phone_number_csv that should then return a JSON object. However in using the request below it simply notes:
E/Volley﹕ [4230] BasicNetwork.performRequest: Unexpected response code 500 for http://(ip-address):3000/getActivatedFriends.json
In testing this request in chromes POSTMAN I know the webservice is correct and should return a JSON object.
How can I make this work?
The POST request in app:
JsonObjectRequest getUserActiveFriends = new JsonObjectRequest(Request.Method.POST, "http://" + Global.getFeastOnline() + "/getActivatedFriends.json",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Parse the JSON:
try {
resultObject = response.getJSONObject("friends_match");
Toast.makeText(getApplicationContext(), resultObject.toString(), Toast.LENGTH_LONG).show();
// PARSE THE REST
//Log.v("USER ID", "The user id is " + userId);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("friends_phone_number_csv", contactsNumbers);
return params;
}
};
requestQueue.add(getUserActiveFriends);
You should add this code, when you post request and return json data, you should add content type "application/json; charset=utf-8" to http header.
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}

Categories

Resources