Adding POST parameters to Android Volley JsonObjectRequest - android

Good afternoon everyone
I did a volley connection to my localserver. It turns out, the connection works fine but my parameters are not getting accepted in my MysqlPHP script.
I believe the parameters are not getting sent correctly.
Here is the code
try {
RequestQueue jr = Volley.newRequestQueue(this);
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
Log.d("The paramet ready", "Ready to go");
JsonObjectRequest jsonObject = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("The response", response.toString());
progressDial.hide();
JSONArray json = null;
try {
json = response.getJSONArray("result");
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (json.getString(0).equalsIgnoreCase("0")) {
Log.d("JsonString: -> ", json.toString());
progressDial.hide();
toast();
} else {
startagain();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
progressDial.hide();
}
}
);
jr.add(jsonObject);

I encountered a similar issue. I had a server API which returned a JSON Object response, so JsonObjectRequest was the go-to request type, but the server didn't like that my body was in JSON format, so I had to make a few changes to my request.
Here's what I did (adapted to your code):
JsonObjectRequest jsonObject = new JsonObjectRequest(Request.Method.POST, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("The response", response.toString());
progressDial.hide();
JSONArray json = null;
try {
json = response.getJSONArray("result");
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (json.getString(0).equalsIgnoreCase("0")) {
Log.d("JsonString: -> ", json.toString());
progressDial.hide();
toast();
} else {
startagain();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
progressDial.hide();
}
}
)
{
#Override
public byte[] getBody()
{
try
{
final String body = "&username=" + username + // assumes username is final and is url encoded.
"&password=" + password // assumes password is final and is url encoded.
return body.getBytes("utf-8");
}
catch (Exception ex) { }
return null;
}
#Override
public String getBodyContentType()
{
return "application/x-www-form-urlencoded";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError
{
Map<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
return headers;
}
};
Here, I'm not sending any JSON Object as the post body, but instead, I'm creating the post body on my own, form url encoded.
I'm overriding the following methods:
getBody - I'm creating the body of the post exactly the way the server wanted it - form url encoded.
getBodyContentType - I'm telling the server what the content type of my body is
getHeaders - I'm telling the server to return the result in JSON format. This might not be necessary for you.

If your API return a JSON array, then you should use a JsonArrayRequest, not a JsonRequest.

Related

How to fix JSONException Error in Volley library?

I am trying to send a JSON object request with two parameters and in response trying to get an array from the api call. However, I am getting exception parse error in Error listener. A post request is sent when the button is clicked. The func takes two parameters but fails to get response, the function directly goes to on response error listener
private void validate_log(String num) {
/*buttonNumCheck.setVisibility(View.INVISIBLE);
final ProgressBar pBar=(ProgressBar)findViewById(R.id.progressBarLogin);
pBar.setVisibility(View.VISIBLE);*/
buttonNumCheck.setInProgress(true);
buttonNumCheck.setEnabled(false);
final String Org_id="81";
final String url="http://xya/api";
RequestQueue rq=Volley.newRequestQueue(this);
JSONObject js=new JSONObject();
try {
js.put("parm1", num);
js.put("parm2", Org_id);
final String requestBody=js.toString();
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjReq=new JsonObjectRequest(
Request.Method.POST, url, js,
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
buttonNumCheck.setEnabled(true);
buttonNumCheck.setInProgress(false);
String stresponse=response.toString();
Toast.makeText(getApplicationContext(),"REPOSE="+response,Toast.LENGTH_SHORT).show();
System.out.println("RESPONSE= "+response);
try {
JSONArray heroArray = response.getJSONArray("");
// Toast.makeText(DeviceCheck_Activity.this, "Welcome Back"+ [1], Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
Log.e("Error", "Response Error", e);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(DeviceCheck_Activity.this, "Response error= " + error, Toast.LENGTH_LONG).show();
/*mdToast=MDToast.makeText(getApplicationContext(), "Oops something went wrong!!",
Toast.LENGTH_SHORT, MDToast.TYPE_ERROR);
mdToast.show();*/
buttonNumCheck.setInProgress(false);
buttonNumCheck.setEnabled(true);
Log.e("Error", "Response Error", error);
}
}) {
#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;
}
};
jsonObjReq.setShouldCache(false);
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rq.add(jsonObjReq);
}
The error response I am getting is
com.android.volley.ParseError: org.json.JSONException: Value [{"store_id":11,"store_name":"Gomati District Main Store"},{"store_id":13,"store_name":"Main Seed Store"}] of type org.json.JSONArray cannot be converted to JSONObject
Your Problem can be solved in 2 ways :
First:)
Using JSONArrayRequest instead of JSONbjectRequest.
Your JSONObjectRequest returns an JSONObject response while your response is an JSONArray therefore java can not convert it and your application crashes.
Change you request as below:
JSONArrayRequest jsonArrReq=new JSONArrayRequest(//changed
Request.Method.POST, url, js,
new Response.Listener<JSONArray>() {
public void onResponse(JSONArray response) {
JSONArray heroArray = response;//changeed
/* rest of your code */
} catch (JSONException e) {
e.printStackTrace();
Log.e("Error", "Response Error", e);
}
}
},
jsonArrReq.setShouldCache(false);
jsonArrReq.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rq.add(jsonArrReq);
Second :)
Using StringRequest instead of JSONObjectRequest. String request returns an String response which lets you do what ever you want with your response.
Change you request as below :
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONArray heroArray = new JSONArray(response);
/* rest of your code */
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", "Response Error", error);
/*rest of your code */
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : js.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", js, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
}
stringRequest.setShouldCache(false);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rq.add(stringRequest);
Use the JsonArrayRequest like thisas your response is JsonArray .
JsonArrayRequest jsonObjReq = new JsonArrayRequest(Request.Method.POST, url, js,
new Response.Listener<JSONArray>() {
public void onResponse(JSONArray response) {
buttonNumCheck.setEnabled(true);
buttonNumCheck.setInProgress(false);
String stresponse = response.toString();
try {
for (int i = 0; i < response.length(); i++) {
JSONObject object = response.getJSONObject(i);
String id = object.getString("store_id");
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("Error", "Response Error", e);
}
}
}
Tried all the solutions didn't worked but thank you guys for your help. I actually found the solution from another question posted in stack overflow page. Here is the solution:
RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//JSONArray jsonArray_1=new JSONArray(response);
System.out.println("RESPONSE= " + response);
JSONArray jsonArray=new JSONArray(response);
json_stringarr=new String[jsonArray.length()];
if(jsonArray.length()>0) {
for (int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
//String web_page=jsonObject1.getString("awb_no");
String store_id=jsonObject1.getString("store_id");
String store_name=jsonObject1.getString("store_name");
json_stringarr[i]=store_id+" - "+store_name;
Toast.makeText(getApplicationContext(), "RESPOBBSE= " + json_stringarr[i], Toast.LENGTH_SHORT).show();
System.out.println("JSON ARRAY=" + json_stringarr[i]);
System.out.println("JSON Object=" + jsonObject1);
}
}
else{
Toast.makeText(getApplicationContext(),"Login ceredentils are incorrect",Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
MDToast mdToast=MDToast.makeText(getApplicationContext(), "Something went wrong!!", Toast.LENGTH_SHORT, MDToast.TYPE_WARNING);
mdToast.show();
error.printStackTrace();
}
}) {
#Override
public byte[] getBody() {
// String body="{\"param1\":"+num+",\"param2\":\"81"\"}";
String body="{\"parm1\":"+num+",\"parm2\":\"81\"}";
return body.getBytes();
}
/*#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("param1", num);
params.put("param2", Org_id);
return params;
}*/
#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;
}
};
I did it by sending a String request and then overriding the getBody() method and then it worked like a charm. Thanks again for all your help.

No response after putting in Header in request

My code as follows:
public void getProfile(){
String LOGIN_REQUEST_TAG = "LOGIN_REQUEST_TAG";
String url = Constants.API_URL + "/users/profile";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Login Response:", response.toString());
JSONObject responseOject = response;
if(responseOject.has("response")){
try {
Log.d("Data Response", responseOject.getString("response"));
} catch (JSONException e) {
e.printStackTrace();
}
}else if(responseOject.has("error")){
try {
errorMessage = responseOject.getString("error");
new AlertDialog.Builder(MainActivity.this)
.setTitle("Error")
.setMessage(errorMessage)
.setNegativeButton("OK", null)
.show();
} catch (JSONException e) {
e.printStackTrace();
}
}else{
//Server error. Come back again later
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error at login: ", error.getMessage());
}
/**
* Passing some request headers
*/
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "Bearer DGZjaza3saxL98g9ATRUQsolCxEZPBUd");
return headers;
}
});
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest,LOGIN_REQUEST_TAG);
The code works initially but after we added headers which are required by the api request, the code above didn't seem to work.
Did I write the headers code above wrongly? Thanks for your help.
Error from logcat as follows:
BasicNetwork.performRequest: Unexpected response code 401
i think you shouldn't place the getHeader() inside the constructor of JsonObjectRequest. It should be placed inside the anonymous class block
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET,
url,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Login Response:", response.toString());
JSONObject responseOject = response;
if(responseOject.has("response")){
try {
Log.d("Data Response", responseOject.getString("response"));
} catch (JSONException e) {
e.printStackTrace();
}
}else if(responseOject.has("error")){
try {
errorMessage = responseOject.getString("error");
new AlertDialog.Builder(MainActivity.this)
.setTitle("Error")
.setMessage(errorMessage)
.setNegativeButton("OK", null)
.show();
} catch (JSONException e) {
e.printStackTrace();
}
}else{
//Server error. Come back again later
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error at login: ", error.getMessage());
}
}
){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "Bearer DGZjaza3saxL98g9ATRUQsolCxEZPBUd");
return headers;
}
};
In case you wanna learn more, the inheritance hierarchy of JsonObjectRequest in volley is Request -> JsonRequest -> JsonObjectRequest . The method you are overriding getHeaders() is derived from the Request base class.

Android Volley calling oData using Request.POST giving 403 Error

I am calling SAP's oData Service using Volley API from Android and getting HTTP 403 Error for the Request.POST. But for the Request.GET for another Service program is working fine. May I know if there is any issue with my code calling oData Service.
Iam passing MYSAPSSO2 token and CSRF Token obtained from my first request call. But getting Authentication error. Any idea what is missing here?
Same oData POST service using JQUERY/SAPUI5 is working fine without any issues.
try {
/** json object parameter**/
JSONObject jsonObject = new JSONObject();
jsonObject.put("SO", so);
jsonObject.put("STATUS", status);
jsonObject.put("NET_VALUE", amount);
Log.i("XXXX", thisMethod+"jsonObject params"+ jsonObject.toString() + "");
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonRespObj) {
Log.i("XXXX", thisMethod+"Response from notification service: " + jsonRespObj.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.i("XXXXX", thisMethod+"Error Response: " + volleyError);
volleyError.printStackTrace();
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
if (mysapsso2 != null) {
Log.i("XXX", thisMethod+"MYSAPSSO2 is : " + TokenHandler.getMYSAPSSO2Token());
Log.i("XXXX", thisMethod+"X-CSRF-Token is : " + TokenHandler.getCSRFToken());
params.put("Cookie", ServiceClass.mysapsso2);
params.put("X-CSRF-Token", TokenHandler.getCSRFToken());
params.put("contentType", "application/json");
}
return params;
}
};
queue.add(jsonObjectRequest);
} catch (JSONException e) {
Log.e("XXX", thisMethod+"There was an error => " + e.getMessage());
e.printStackTrace();
}
catch (Exception e) {
Log.e("XXXX", thisMethod+"There was an error => " + e.getMessage());
e.printStackTrace();
}
Use StringRequest insted of JsonObjectRequest. Get json encoded response to a string & create json object. Below code work fine for me. try it.
public void getPostJsonData() {
final String URL = "URL";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
JSONArray jsonArray = obj.getJSONArray("server_response");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject JO = jsonArray.getJSONObject(i);
fname = JO.getString("firstname"); //or JO.toString()
lname = JO.getString("lastname");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ActivityName.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("Cookie", ServiceClass.mysapsso2.toString);
hashMap.put("X-CSRF-Token", TokenHandler.getCSRFToken().toString);
hashMap.put("contentType", "application/json");
return hashMap;
}
};
final RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
requestQueue.addRequestFinishedListener(new RequestQueue.RequestFinishedListener<Object>() {
#Override
public void onRequestFinished(Request<Object> request) {
requestQueue.getCache().clear();
}
});
}

Android Json Arraylist to Server with Restful Web service

This is my Arraylist which I get from the previous fragment,
listoftags = getArguments().getParcelableArrayList("data");
It works well. Now I have to send this with some parameters like below:
public void volleyJsonObjectRequest(final String SessionID , final String CustomerID, final String ServiceState , final String ServiceID, final String Address, final String PaymentMode, final String CustomerComments , final ArrayList Items){
String REQUEST_TAG = "volleyJsonObjectRequest";
// POST parameters
CustomRequest request = new CustomRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Toast.makeText(SignActivity.this, response.toString(), Toast.LENGTH_SHORT).show();
Log.d("response",""+response.toString());
/* String status = response.optString("StatusMessage");
String actionstatus = response.optString("ActionStatus");
Toast.makeText(getActivity(), ""+status, Toast.LENGTH_SHORT).show();
if(actionstatus.equals("Success"))
{
// Intent i = new Intent(SignActivity.this, LoginActivity.class);
// startActivity(i);
// finish();
}*/
dismissProgress();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error."+error.toString(), Toast.LENGTH_SHORT).show();
Log.d("response",""+error.toString());
dismissProgress();
}
}) {
/* #Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}*/
public String getBodyContentType()
{
return "application/json; charset=utf-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
JSONArray jsArray = new JSONArray(listoftags);
params.put("SessionID", SessionID);
params.put("CustomerID", CustomerID);
params.put("ServiceState", ServiceState);
params.put("ServiceID", ServiceID);
params.put("Address", Address);
params.put("PaymentMode",PaymentMode);
params.put("CustomerComments",CustomerComments);
params.put("Items",jsArray.toString());
return params;
}
};
AppSingleton.getInstance(getActivity().getApplicationContext())
.addToRequestQueue(request, REQUEST_TAG);
}
but it getting error to me I want to send it like
// server side //
{
"SessionID":"9lm5255sg0ti9",
"CustomerID":"9",
"ServiceState":"Karnataka",
"ServiceID":"3",
"Address":"sfaff",
"PaymentMode":"cash",
"CustomerComments":"this is fine",
"Items":[
{
"ItemId":1,
"Cost":6777,
"Quantity":33333
}
]
}
How can send arraylist, with other strings, as raw data using volley on server.
JsonObjectRequest can be used to execute rest api using json as input.
JsonObject jobj = new JsonObject();
jobj.put("key","value");
jobj.put("key","value");
jobj.put("key","value");
jobj.put("key","value");
JsonObjectRequest request = new JsonObjectRequest(requestURL, jobj, new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
}
});
*Now add this request in request queue of volley.*
Here jobj is containing input parameters. It can contain even json array inside a JsonObject. Let me know in case of any query.
Rather then volley try retrofit. Make pojo model of your object you want to send, you can make that from pojo classes from https://www.jsonschema2pojo.org the send the whole object on restapi
// try the request //
try {
REQUEST QUEUE
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
String URL = url;
JSONObject jsonBody = new JSONObject();
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
Iterator itr = listoftags.iterator();
while(itr.hasNext()){
AddRowItem ad=(AddRowItem)itr.next();
jsonObject.put("ItemId:",1);
jsonObject.put("Cost:",ad.getPrices());
jsonObject.put("Quantity:",ad.getQty());
// Log.d("ItemId:",""+1+" "+"Cost:"+ad.getPrices()+" "+"Quantity:"+ad.getQty());
}
jsonArray.put(jsonObject);
JSON VALUES PUT
jsonBody.put("SessionID", "9kp0851kh6mk3");
jsonBody.put("CustomerID", "9");
jsonBody.put("ServiceState", "Karnataka");
jsonBody.put("ServiceID", "3");
jsonBody.put("Address", "Address Demo");
jsonBody.put("PaymentMode", "cost");
jsonBody.put("CustomerComments", "Android Volley Demo");
jsonBody.put("Items", jsonArray);
final String requestBody = jsonBody.toString();
Log.d("string ---- >",""+requestBody);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
showToast("get value"+response.toString());
try {
JSONObject jObj = new JSONObject(response);
String action = jObj.get("ActionStatus").toString();
String status = jObj.getString("StatusMessage");
{"ActionStatus":"Success","StatusMessage":"Order Created","RefIDName":"OrderID","RefIDValue":19}
showToast("get value"+action);
}
catch (JSONException e)
{
showToast("get error"+e.toString());
Log.d("errorissue",""+e.toString());
}
dismissProgress();
}
}, new Response.ErrorListener() {
// error response //
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
showToast("get error"+error.toString());
dismissProgress();
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
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;
}
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
dismissProgress();
}
}
}
// THIS IS THE WAY ISSUE RESLOVED //
THANKS EVERYONE ...

Android Volley - BasicNetwork.performRequest: Unexpected response code 400

Problem statement:
I am trying to access an REST API that will return a JSON object for various HTTP status codes (400, 403, 200 etc) using Volley.
For any HTTP status other than 200, it seems the 'Unexpected response code 400' is a problem. Does anyone have a way to bypass this 'error'?
Code:
protected void getLogin() {
final String mURL = "https://somesite.com/api/login";
EditText username = (EditText) findViewById(R.id.username);
EditText password = (EditText) findViewById(R.id.password);
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", username.getText().toString());
params.put("password", password.getText().toString());
JsonObjectRequest req = new JsonObjectRequest(mURL, new JSONObject(
params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject obj = response
.getJSONObject("some_json_obj");
Log.w("myApp",
"status code..." + obj.getString("name"));
// VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.w("error in response", "Error: " + error.getMessage());
}
});
// add the request object to the queue to be executed
AppController.getInstance().addToRequestQueue(req);
}
One way of doing this without changing Volley's source code is to check for the response data in the VolleyError and parse it your self.
As of f605da3 commit, Volley throws a ServerError exception that contains the raw network response.
So you can do something similar to this in your error listener:
/* import com.android.volley.toolbox.HttpHeaderParser; */
public void onErrorResponse(VolleyError error) {
// As of f605da3 the following should work
NetworkResponse response = error.networkResponse;
if (error instanceof ServerError && response != null) {
try {
String res = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, "utf-8"));
// Now you can use any deserializer to make sense of data
JSONObject obj = new JSONObject(res);
} catch (UnsupportedEncodingException e1) {
// Couldn't properly decode data to string
e1.printStackTrace();
} catch (JSONException e2) {
// returned data is not JSONObject?
e2.printStackTrace();
}
}
}
For future, if Volley changes, one can follow the above approach where you need to check the VolleyError for raw data that has been sent by the server and parse it.
I hope that they implement that TODO mentioned in the source file.
#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;
}
You need to add Content-Type to the header.
Me too got the same error but in my case I was calling url with blank spaces.
Then, I fixed it by parsing like below.
String url = "Your URL Link";
url = url.replaceAll(" ", "%20");
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
...
...
...
Try this ...
StringRequest sr = new StringRequest(type,url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// valid response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
params.put("grant_type", "password");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
// Removed this line if you dont need it or Use application/json
// params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
You mean that want to get status codes?
VolleyError has a member variable type of NetworkResponse and it is public.
You can access error.networkResponse.statusCode for http error code.
I hope it is helpful for you.
What I did was append an extra '/' to my url, e.g.:
String url = "http://www.google.com"
to
String url = "http://www.google.com/"
in my case, I was not writing reg_url with :8080 .
String reg_url = "http://192.168.29.163:8080/register.php";
change
public static final String URL = "http://api-Location";
to
public static final String URL = "https://api-Location"
it's happen because i'm using 000webhostapp app
Just to update all, after some deliberations, I have decided to use Async Http Client instead to solve my earlier problem. The library allows a cleaner approach (to me) to manipulate HTTP responses especially in cases where JSON objects are returned in all scenarios/HTTP statuses.
protected void getLogin() {
EditText username = (EditText) findViewById(R.id.username);
EditText password = (EditText) findViewById(R.id.password);
RequestParams params = new RequestParams();
params.put("username", username.getText().toString());
params.put("password", password.getText().toString());
RestClient.post(getHost() + "api/v1/auth/login", params,
new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers,
JSONObject response) {
try {
//process JSONObject obj
Log.w("myapp","success status code..." + statusCode);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers,
Throwable throwable, JSONObject errorResponse) {
Log.w("myapp", "failure status code..." + statusCode);
try {
//process JSONObject obj
Log.w("myapp", "error ..." + errorResponse.getString("message").toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}

Categories

Resources