This question already has answers here:
Getting headers from a response in volley
(2 answers)
Closed 6 years ago.
Can someone please guide me that how to get the header value from the url. I have referred to many tutorials but i could not find any tutorial to get the header value from json. Any help would be highly appreciated.
Here is my code:
JsonArrayRequest obreq = new JsonArrayRequest(Request.Method.GET, JsonURL,
// The third parameter Listener overrides the method onResponse() and passes
//JSONObject as a parameter
new Response.Listener<JSONArray>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONArray response) {
pbHeaderProgress.setVisibility(View.GONE);
try {
// Retrieves the string labeled "colorName" and "description" from
//the response JSON Object
//and converts them into javascript objects
for (int i = 0; i < response.length(); i++) {
JSONObject jresponse = response.getJSONObject(i);
String id = jresponse.getString("id");
Id.add(id);
String auth = jresponse.getString("DJ_author_name");
Author.add(auth);
String date = jresponse.getString("date_gmt");
SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
java.util.Date date4 = null;
try {
date4 = form.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
Date.add(newDateStr);
JSONObject title = jresponse.getJSONObject("title");
String tit = title.getString("rendered");
Title.add(tit);
JSONObject img = jresponse.getJSONObject("better_featured_image");
String pic = img.getString("source_url");
Image.add(pic);
}
// Adds strings from object to the "data" string
linear.setVisibility(RelativeLayout.VISIBLE);
// Adds the data string to the TextView "results"
adapter.notifyDataSetChanged();
}
// Try and catch are included to handle any errors due to JSON
catch (JSONException e) {
// If an error occurs, this prints the error to the log
e.printStackTrace();
}
}
},
// The final parameter overrides the method onErrorResponse() and passes VolleyError
//as a parameter
new Response.ErrorListener() {
#Override
// Handles errors that occur due to Volley
public void onErrorResponse(VolleyError error) {
pbHeaderProgress.setVisibility(View.GONE);
Toast.makeText(Home.this, "error!!! =)",
Toast.LENGTH_SHORT).show();
noi.setVisibility(RelativeLayout.VISIBLE);
Log.e("Volley", "Error");
}
}
);
obreq.setRetryPolicy(new DefaultRetryPolicy(
30000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adds the JSON object request "obreq" to the request queue
requestQueue.add(obreq);
You can subclass Request (or any of its subclasses) and override the parseNetworkResponse method:
#Override
protected Response<Bitmap> parseNetworkResponse(NetworkResponse response)
{
Map<String, String> responseHeaders = response.headers;
}
with reference to this stackoverflow's link
please check djodjos answer here
if you mean you want to get the header values of the json that is returned itself, not the headers of the request itself you can use Gson library it's fast reliable and very easy to use
------- Ok then as djodjos answer
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
JSONObject jsonResponse = new JSONObject(jsonString);
jsonResponse.put("headers", new JSONObject(response.headers));
return Response.success(jsonResponse,
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
} }
you need to override parseNetworkResponse when you create the new JsonArrayRequest (obreq )
for example
StringRequest request=new StringRequest(GET,"url",listener,errorListener){
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String totalPages=responseHeaders.get("X-WP-TotalPages");
return super.parseNetworkResponse(response);
}
};
Related
Below is the response what i am getting i want to get the data from "SourceJson" m not ble to understnd why i am getting "" in source json please help me
{
"incomingOrder": [
{
"Namw": 8510,
"Surname": "00",
"mob": "00",
"phone": "000",
"SourceJson": "{\"cart_gst\":30.21,\"instructions\":\"\",\"order_packing_charges\":30,\"cart_igst_percent\":0,\"cart_sgst\":15.1038,}",
"test": "NotSynced",
"test": "DPA",
}]}
Try this code :
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest obreq = new JsonObjectRequest(Request.Method.GET, JsonURL,
// The third parameter Listener overrides the method onResponse() and passes
//JSONObject as a parameter
new Response.Listener<JSONObject>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("incomingOrder");
JSONObject jsonObject = jsonArray.getJSONObject(0);
JSONObject objSourceJson=jsonObject.getJSONObject("SourceJson");
Log.i("IvaSourceJson",objSourceJson.toString());
String cart_gst=objSourceJson.getString("cart_gst");
String instructions=objSourceJson.getString("instructions");
}
// Try and catch are included to handle any errors due to JSON
catch (JSONException e) {
// If an error occurs, this prints the error to the log
e.printStackTrace();
}
}
},
// The final parameter overrides the method onErrorResponse() and passes VolleyError
//as a parameter
new Response.ErrorListener() {
#Override
// Handles errors that occur due to Volley
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
// Adds the JSON object request "obreq" to the request queue
requestQueue.add(obreq);
As it is JSONArray data is of list type, better not to use jsonArray.getJSONObject(0);.
Use this code for multiple results,
StringRequest request = new StringRequest(Request.Method.GET, "", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
try {
JSONObject object = new JSONObject(response);
JSONArray array = object.getJSONArray("incomingOrder");
for (int i = 0; i < array.length(); i++){
JSONObject object1 = array.getJSONObject(i);
String name = object1.getString("Namw");
String surname = object1.getString("Surname");
String mob = object1.getString("mob");
String phone = object1.getString("phone");
String sourceJson = object1.getString("SourceJson");
String test = object1.getString("test");
String test1 = object1.getString("test");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.getMessage());
}
});
Context context;
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(request);
Code this in any method and call the method where the action needed.
I am trying to post Json data via Android Volly library but getting an error.
Here is my Json body which perfectly working with Postman.
{
"fullName": "Mr X",
"fatherName": "Mr Y",
"motherName": "Mrs Z",
"nidNo": "34345",
"surveyDate": "2020-03-25",
"birthCertificateNo": "3435355",
"mobileNumber": "01834261758",
"dateOfBirth": "",
"gender": "Male",
"bloodGroup": "A+",
"numOfDaysSick": "23",
"numOfContInftPerson": "0",
"remarks": "Need Rest",
"physicalSymptoms": ",Runny nose,Sore throat",
"status": "User",
"isForeignVisitor": "false",
"isRead": "false",
"presentAddress": {
"village": "Sonapur",
"postOffice": "Noahat",
"postCode": "1219",
"upazila": "Sonaimuri",
"district": "Noakhali",
"division": "Chittagong"
},
"permanentAddress": {
"village": "Sonapur",
"postOffice": "Noahat",
"postCode": "1234",
"upazila": "Sonaimuri",
"district": "Noakhali",
"division": "Chittagong"
}}
But when i try to send it via Android Volly's Post call I am getting the error below :
com.android.volley.ParseError: org.json.JSONException: Value Survey of type java.lang.String cannot be converted to JSONObject
Here is my Android method to generate this Json body.
Note that : I can successfully generate Json body with this Android method and copy paste(from Logcat) to Postman, it works fine. But Android Volly giving me such error. My url is also ok because I tested it manually.
public void SendSurveyDataToServer(){
customProgressBar.show();
//--
//-------------------------------
JSONObject permanent_address = new JSONObject();
try {
permanent_address.put("village", village_pS);
permanent_address.put("postOffice", post_office_pS);
permanent_address.put("postCode", post_code_pS);
permanent_address.put("upazila", upazilla_pS);
permanent_address.put("district", district_pS);
permanent_address.put("division", division_pS);
} catch (JSONException e) {
e.printStackTrace();
}
//--
JSONObject present_address = new JSONObject();
try {
present_address.put("village", village_tS);
present_address.put("postOffice", post_office_tS);
present_address.put("postCode", post_code_tS);
present_address.put("upazila", upazilla_tS);
present_address.put("district", district_tS);
present_address.put("division", division_tS);
} catch (JSONException e) {
e.printStackTrace();
}
//--
if(numberofContactedPersonS.equals("Yes")){
numberofContactedPersonS = "true";
}else{
numberofContactedPersonS = "false";
}
//--
//--
JSONObject parameters = new JSONObject();
try {
parameters.put("fullName", fullNameS);
parameters.put("fatherName", fatherNameS);
parameters.put("motherName", motherNameS);
parameters.put("nidNo", nidNoS);
parameters.put("surveyDate", "2020-03-25");
parameters.put("birthCertificateNo", birthdayCertificateNoS);
parameters.put("mobileNumber", mobileNoS);
parameters.put("dateOfBirth", "");
parameters.put("gender", gender_selectS);
parameters.put("bloodGroup", blood_group_selectS);
parameters.put("numOfDaysSick", sickDaysNoS);
parameters.put("numOfContInftPerson", "0");
parameters.put("remarks", remarksS);
parameters.put("physicalSymptoms", physicalSymptomsS);
parameters.put("status", statusS);
parameters.put("isForeignVisitor", numberofContactedPersonS );
parameters.put("isRead", "false");
parameters.put("presentAddress", present_address);
parameters.put("permanentAddress", permanent_address);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d(classTag,parameters.toString());
RequestQueue rq = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.POST, ApiClass.server_path+ApiClass.saveSurvey, parameters, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String respo=response.toString();
Log.d(classTag,respo);
//iosDialog.cancel();
//Parse_signup_data(respo);
Log.e(classTag,respo);
if(respo.equalsIgnoreCase("Survey Info save Successfully")){
Toast.makeText(Survey.this,"Your survey submitted successfully. Thank you!",Toast.LENGTH_LONG).show();
//----------------------------------------
}else if(respo.equalsIgnoreCase("Survey Info already exits")){
Toast.makeText(Survey.this,"Survey info already exist with this NID and Birth Certificate Number!",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(Survey.this,"There is an error while submitting your survey, please try again!",Toast.LENGTH_LONG).show();
Log.e(classTag,"There is an error while submitting your survey, please try again!");
}
customProgressBar.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
// Toast.makeText(MainActivity.this,"Can't connect with server! Please check your network connection.",Toast.LENGTH_LONG).show();
customProgressBar.hide();
Log.d(classTag,error.toString());
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(30000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rq.getCache().clear();
rq.add(jsonObjectRequest);
//--------------
}
After searching for 3 days I found that the problem is API response. It was giving me 'Success' and 'Failed' in byte format but I was always checking the response for JSONObject or at least String. Postman converted the byte data into string automatically and showed me, for that reason I thought server was giving me the response in string format.
However, I sent the Json request by Volly's String Request and track the response. Then I found what is messing with me! Our backend developer might be lazy to give a response in String or Json format.
I got the response by converting byte to string :
String string = new String(response.data, StandardCharsets.UTF_8);
Here is my modification for this :
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = ApiClass.server_path+ApiClass.saveSurvey;
final String requestBody = parameters.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
customProgressBar.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
customProgressBar.hide();
}
}) {
#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;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
//customProgressBar.hide();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
String string = new String(response.data, StandardCharsets.UTF_8);
Log.e(classTag,string);
serverMsg = string;
showServerMsgNow = true;
Log.e(classTag,"Server msg : "+serverMsg+" server show : "+showServerMsgNow);
// ShowServerResponse();
}
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));
}
};
requestQueue.add(stringRequest);
I am familiar with Volley and creating a Singleton class, and adding requests to the queue. However, I wish to increase the modularity of volley and simply call all requests through method call to another class instead. I have setup the present action as basis for the common GET request:
public Object getRequest(String params) {
final JSONObject getRequestReturn = new JSONObject();
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET,
VolleySingleton.prefixURL, ((String) null),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Parse the JSON:
try {
getRequestReturn = response;
Log.v("GET Request value", response.toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("GET Request Error", error.toString());
}
});
mRequestQueue.add(getRequest);
return getRequestReturn;
}
However, I have a the perplexing catch 22 error on the assignment of response at:
getRequestReturn = response;
The error notes that getRequestReturn must be declared final to allow for use within the inner class, but upon assigning final, another error appears noting that you cannot assign a value to a final variable.
How can this method be handled?
Declare JSONObject as global and initialize in same place like this.
JSONObject getRequestReturn ;
getRequestReturn = new JSONObject();
public Object getRequest(String params) {
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET,
VolleySingleton.prefixURL, ((String) null),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Parse the JSON:
try {
Log.v("GET Request value", response.toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("GET Request Error", error.toString());
}
});
mRequestQueue.add(getRequest);
return new JSONObject();
}
U can't get response when u return!Volley request is async!
I use EventBus and I do it like this :
When I need to get data from web , i add a request like this.
Then when i get response from web ,I use EventBus to post a event.
I get the event and update my page.
Or U can try the RxAndroid.
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.
I know its a repetitive question, but still. Can any one provide me a solution or workaround to get status code returned with the response when we make a network rest api call?
Here provided a work around. But I didn't understood. Can any one explain me in a better way the solution.?
The rest api returns many success status code like 201,204 and many server errors.
I want to check status code before proceeding and have to make decision accordingly.
This is my existing code.
on a button click
RequestQueue queue;
queue = Volley.newRequestQueue(this);
final String[] token = new String[1];
String status;
String url = "http://myapiurl";
JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
// want to get status code here
token[0] = response.getString("message");
Toast.makeText(getApplicationContext(),token[0],Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", String.valueOf(error));
}
}
);
queue.add(postRequest);
EDIT: previously didn't answer the question at all.
It seems nontrivial to do this while using the clean Listener interfaces, but it's also possible to implement this as a custom request (the examples specifically show parsing JSON). You can look at the JsonObjectRequest and JsonRequest sources for inspiration.
You should end up with something like this (heavily inspired by JsonObjectRequest):
Request<JSONObject> request = new Request<JSONObject>() {
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(
response.data,
HttpHeaderParser.parseCharset(response.headers));
JSONObject obj = new JSONObject(jsonString);
// can access response.statusCode here
// ...
return Response.success(obj, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
};