Handle service call using volley library. Its working fine for jsonObject, jsonArray and String request but my application have one service different request and response. In this service have post params are Jsonobject, and return response is String.
I am trying many solution to handle response.but no one working. I am new android application developer.
post param and response:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return getHeader();
}
};
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 48, 2, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleyRequest.volleyRequestInstance(mContext).addToRequestQueue(jsonObjectRequest);
Volley Parse error will occur in different scenarios
If you call post method as to get, and also get as post
You have tried to pass different payloads
Return values are different in types that you are expected
Use a custom request to solve this issue in normal cases example here:
https://developer.android.com/training/volley/request-custom
in your code.
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> myHeader=new HashMap<>();
myHeader.put("Accept","text");
return myHeader;
}
};
jsonObjectRequest.setRetryPolicy(new
DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 48,
2,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleyRequest.volleyRequestInstance(mContext).addToRequestQueue
(jsonObjectRequest);
also needs your 'params' value for further clarification
Check on the response the URL returns the problem might be not the code but the URL response.
In my case Volley failed to parse my response because it did not understand the response from the URL.
hope this answer will help someone good luck :)
Related
I need to send a request that authorizes the user by providing a bearer token. How can i add a header to my request that contains this bearer token.
This is what my request looks like:
JsonObjectRequest jsonObjReq2 = new JsonObjectRequest(Request.Method.POST,
personUrl, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//something
}
});
You can override one more method, which is getHeaders().
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
params.put("Accept-Language", "en"); //add as many headers as you want
return params;
}
Little tip here is, stop using volley and use Retrofit Instead. Its much better, clean and easy.
You can check this course to learn retrofit in detail: Android Retrofit Tutorial.
I'm trying to use the speech recognition REST API service from wit.ai
I have used Volley to send a POST request to the URL
https://api.wit.ai/speech
This is what I have currently done:
void makeApiCall(){
StringRequest request = new StringRequest(Request.Method.POST, "https://api.wit.ai/speech", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("wit_response",response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("wit_response",error.toString());
}
}){
#Override
protected Map<String,String> getParams() throws AuthFailureError{
Map<String,String> params = new HashMap<>();
params.put("Authorization","Bearer XXXXXX"); //hidden my token
params.put("Content-Type","audio/mpeg3");
return params;
}
#Override
public byte[] getBody() throws AuthFailureError {
return sendToByte();
}
};
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(request);
}
I am receiving an error of com.android.volley.ClientError on the wit_response log key inside onErrorResponse() method
I have not missed the content type and authorization header, and my sendToByte function is succesfully returning an mp3 file converted to byte array.
What is the issue?
I had to use this link https://gist.github.com/anggadarkprince/a7c536da091f4b26bb4abf2f92926594
And use MultiPartRequest class as described in this to upload my file.
Please comment here if you need any assistance (for all future folks)
I'm going to send a JsonObjectRequest to the server as form-data using Volley Library. I Checked similar questions. none of them covers my problem.
This is Postman ScreenShot of the exact request that I need:
This is My JSONObject named myKey which contains a JSONArray:
{
"myArray":[
{
"code":"FA95",
"id":"94"
}
]
}
and this is my request method:
public static void getSomething(String url) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public byte[] getBody() {
return super.getBody();
}
};
request.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(request);
}
Should I override getBody() or not? and what should it return exactly?
Here is the answer: https://stackoverflow.com/a/39718240/3024933
You need to override the getParams() method and use StringRequest instead of JsonObjectRequest.
So I was using API request in spoonucalur, which is a recipe api that provide recipe. I tried the get request inside postman and it works fine. However, it works so unstable in my app. I am using android studio, using volley for the library to handle the get request.
JsonArrayRequest getRequest = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
callbackHelper.onSuccess(response.getJSONObject(0));
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error", error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("X-Mashape-Key", currentAPI);
params.put("Accept", "application/json");
return params;
}
};
Log.d("request", "starting");
queue.add(getRequest);
Sometimes it return me the correct information, but sometimes it will just say timeOutError. It returns pretty fast inside postman for my request, therefore I have no idea why it wouldn't work for now.
Here is the api link : https://market.mashape.com/spoonacular/recipe-food-nutrition
Here is the get request that I'm using : https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/findByNutrients?maxCalories=4000&number=1&offset=0&random=true
Change the RetryPolicy on your Request to allow for longer timeouts.
Ex.
final int TIMEOUT_MS = 10000;
getRequest.setRetryPolicy(new DefaultRetryPolicy(TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy. DEFAULT_BACKOFF_MULT);
...
In my php it produce a Json like below and this working fine when I testing in Postman
{"comment_id":8,"commenter_username":"abc","profile_image_path":abc/abc/abc.jpg","comment_body":"adssadasdasdaa","comment_created_at":"2017-03-21 13:03:40"},
But when it parse to volley,it become like this
{"comment":[{"comment_created_at":"2017-03-21 13:03:40","comment_id":8,"comment_body":"adssadasdasdaa","commenter_username":"abc","profile_image_path":"http:\/\/abc\/def\/v1\/abc\/defaultmale.jpg"}
I found many posts in Stackoverflow,so I tried this,which is working well in other activity.
json_encode($response, JSON_UNESCAPED_SLASHES);
Here come in my Dialog Fragment,I made Volley Request,the Json adding backslashes in the URL.
Here is my code in Dialog Fragment,which I think is same like the other Activity.
private void fetchCommentOfPost(int post_id){
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
AppConfig.URL_GET_COMMENT + post_id, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(AppController.TAG, "VolleyResponse: " + response.toString());
Log.d("responseGet",response.toString());
parseJsonFeed(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(AppController.TAG, "Error: " + error.getMessage());
}
}) {
//adding header to authenticate
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
return headers;
}
};
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
Can somebody please tell me how to get rid the backslashes in Json accept what i tried?Cause I totally have no idea.Thanks in advance.