Volley post method return response code 500 - android

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.

Related

Adding parameters on Restful API using JsonObjectRequest on Android Studio

I'm calling a restful api on my android project and I used Volley and JsonObjectRequest, I thought that the third parameter of the JsonObjectRequest which is jsonRequest are the api parameters so I created a json object for that which in the end I only got errors. So is it common to directly add the api parameters on the url? instead of passing it on a json object? what is the third parameter for, it would be really helpful if someone can give me an example. And my last question is how do you get the entire json response instead of using response.getString("title") for each key.
//api parameters directly added on the url
String URL = "https://www.myapi.com/?param=sample&param1=sample1";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String title = response.getString("Title");
Log.d("title", title);
} catch(Exception e){
Log.e("response error", e.toString());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, error.toString());
}
});
Below your Response.ErrorListener() you need to add these two overrides:
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, error.toString());
}) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("param", "sample");
params.put("param1", "sample1);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/x-www-form-urlencoded; charset=UTF-8");
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
return headers;
}
};

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/

Android Volley: POST request - req.body inside of NodeJS REST API empty

I know its been discussed like a billion times, and I have read a couple of questions/answers and this one in particular seemed like a good example -> example. So now I have tried to recreate the code and added my getParams() as well as my getHeaders().
Awkwardly I get a HTTP Status Code 400:
E/Volley: [303] BasicNetwork.performRequest: Unexpected response code 400 for http://10.0.2.2:3000/classes
Since I have created the REST API I can see where this status code 400 comes from, its my NodeJS response if the req.body doesn't contain mAtt, mDatum, mRID, mVon. So now I know that my POST request is not properly working even tho I set my getParams()as well as my getHeaders() ...
Now, my guess would be that I'm setting Params but I'm fetching req.body.mAtt, req.body.mDatum , req.body.mRID, req.body.mVon, that would explain why my NodeJS returns the status code 400. If I fetched req.query.mAtt I would probably get something back?
Is there a certain method that need to be overridden by me, to actually set the body instead of the query params?
This is what my POST req looks like:
JsonObjectRequest JOPR = new JsonObjectRequest(Request.Method.POST,
myAcitveLessonPOSTUrl, null, new Response.Listener<JSONObject>(){
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("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");
return headers;
}
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("mAtt", "+1");
params.put("mDatum", mDatum);
params.put("mRID", mRID);
params.put("mVon", mVon);
return params;
}
};
requestQ.add(JOPR);
Thank you!
I finally got it. I continued to search for answers and stumbled upon this question/answer link.
Since my REST API is looking for req.body variables, the getParams() have no effect. In order to send req.body variables the getBody() method has to be overridden.
So what I basically had to do was:
1) create a JSONObject
2) put my key:values inside the JSONObject
3) get the contents of my JSONObject into a String via toString()
4) #Override the getBody() method inside my JsonObjectRequest
Done.
So my corrected code looks like this:
JSONObject jsonBodyObj = new JSONObject();
try{
jsonBodyObj.put("mAtt", "+1");
jsonBodyObj.put("mDatum",mDatum);
jsonBodyObj.put("mRID",mRID);
jsonBodyObj.put("mVon",mVon);
}catch (JSONException e){
e.printStackTrace();
}
final String requestBody = jsonBodyObj.toString();
JsonObjectRequest JOPR = new JsonObjectRequest(Request.Method.POST,
myAcitveLessonPOSTUrl, null, new Response.Listener<JSONObject>(){
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
populateLessonDetails(myActiveLessonURLFiltered);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("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");
return headers;
}
#Override
public byte[] getBody() {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
requestBody, "utf-8");
return null;
}
}
};
requestQ.add(JOPR);
Kudos to #dvdciri for his original question and Edits, what would eventually become this answer!

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;
}

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