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.
Related
I am trying to do the following task:
I am planning to use JsonObjectRequest (Volley Library) in my code and extract the credentials but I am not able to understand where would the Username and Password be required in the request. This is a code snippet. If anyone can tell where I need to authenticate the Username and Password in this code snippet to fetch the JSON Object, it would be very helpful.
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.wtf(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.wtf(error.getMessage(), "utf-8");
}
});
queue.add(jsonObjectRequest)
This is how you can use POST Method in volley:
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(final String response) {
try {
JSONObject object = new JSONObject(response);
// here is your json object
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// volley errors
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);
return params;
}
};
queue.add(stringRequest);
Create a jsonObject with username and password then pass this object to the JsonObjectRequest
Your code will be like this :
JSONObject body= new JSONObject();
body.put("username", "user");
body.put("password", "userPassword");
JsonObjectRequest jsonObjectRequest= new JsonObjectRequest(Request.Method.POST, url,
body, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.wtf(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.wtf(error.getMessage(), "utf-8");
}
});
queue.add(jsonObjectRequest)
You need to understand what is form-data and how it is used:
Definition and Usage
The method attribute specifies how to send form-data (the form-data is sent to the page specified in the action attribute).
The form-data can be sent as URL variables (with method="get") or as HTTP post transaction (with method="post").
Notes on GET:
Appends form-data into the URL in name/value pairs
The length of a URL is limited (about 3000 characters)
Never use GET to send sensitive data! (will be visible in the URL)
Useful for form submissions where a user wants to bookmark the result
GET is better for non-secure data, like query strings in Google
Notes on POST:
Appends form-data inside the body of the HTTP request (data is not shown in URL)
Has no size limitations
To pass username and password arguments as form-data you can create StringRequest and override it's getParams method to return a map of data.
StringRequest request = new StringRequest(
Request.Method.POST,
requestUrl,
onResultListener,
onErrorListener) {
#Override
protected Map<String, String> getParams() {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("username", username)
hashMap.put("password", password)
return hashMap;
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
// You can parse response here and throw exceptions when required.
return super.parseNetworkResponse(response);
}
};
queue.add(request)
I've got class with simple Json Object Request, this is method where whole request is called, and in LogCat I get only:
Volley: [2] 2.onErrorResponse: Error:
so I don't know where to look for a fix
private void getBeerDetails() {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET,
"https://api.punkapi.com/v2/beers/13",
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
beerName.setText(response.getString("name"));
alc.setText(response.getString("abv"));
ibu.setText(response.getString("ibu"));
firstBrewed.setText(response.getString("first_brewed"));
yeast.setText(response.getString("yeast"));
description.setText(response.getString("description"));
foodPairing.setText(response.getString("food_pairing"));
Picasso.with(getApplicationContext())
.load(response.getString("image_url"))
.into(beerImageView);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error:", error.getMessage());
}
});
requestQueue.add(jsonObjectRequest);
}
As I see here your response is in JsonArray format.
So try with below
private void getBeerDetails() {
JsonArrayRequest jsonObjectRequest = new JsonArrayRequest
(Request.Method.GET,
"https://api.punkapi.com/v2/beers/13",
null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if(response.length()>0){
//make a loop and add item to your list
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error:", error.getMessage());
}
});
requestQueue.add(jsonObjectRequest);
}
Your error message is not very descriptive. However, I think you need to set the content-type to application/json in the header for your GET request. Override the getHeaders function while creating the request. Here's a java example.
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonBody,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
};
Update
As per your comment in the answer, you have failed to parse the JSON which was returned from your GET request. As I have seen from your response JSON, you are receiving an array of objects. I would like to suggest using Gson for JSON parsing. Its simple and easier to implement. You need to define a class containing the fields of the object in your array which is returned in your response. Then just use Gson to convert the values from JSON array into the array of that specific object that you have created. Here's a sample.
Gson gson = new Gson();
Data[] dataArray = gson.fromJson(jsonLine, Data[].class);
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 :)
I've been using the volley library for consuming services with my android app. I noticed something weird,when I try to post a json object to server, I have to make a response Listener of type JSONObject. But my server returns a String, Success or failure. Is it possible to write a JsonObjectRequest which waits for a String response? this is What I have written. The service runs correctly, but the onErrorResponse is triggered after successful post due to cannot converge String to JSON
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, jsonBody,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(StartingActivity.this,response.toString(),Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(StartingActivity.this,"That didn't work",Toast.LENGTH_SHORT).show();
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(jsonRequest);
Use StringRequest instead of JsonObjectRequest. it will return response in string Like this:
StringRequest stringRequest = new StringRequest(Request.Method.POST,url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG,response);
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
//use this to post data.
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
//use this for headers.
}
};
stringRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 50000;
}
#Override
public int getCurrentRetryCount() {
return 50000;
}
#Override
public void retry(VolleyError error) throws VolleyError {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
The jsonBody your sending to server it should be in String.
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, jsonBody.toString(),
I hope this will help you. Thanks!
I have to make a json post request with the following parameters.
{"method":"login","data":{"username":"korea","password":"123456"}}
I use volley to make post request and follwoing is my code to do post request.
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, loginURL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(mContext,response.toString(),Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map = new HashMap<String,String>();
map.put("method","login");
map.put("username","korea");
map.put("password","123456");
return map;
}
};
requestQueue.add(jsonObjectRequest);
requestQueue.start();
Im getting error response from server. How to get proper response from server?
Change Request.Method.GET to Request.Method.POST. Then pass a JSONObject as the third parameter where you currently have null;
For example:
JSONObject data = new JSONObject();
data.put("username","korea");
data.put("password","123456");
JSONObject jsonObject = new JSONObject();
jsonObject.put("method","login");
jsonObject.put("data",data);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, loginURL, jsonObject, responseListener, errorListener);
I use volley to make post request and follwoing is my code to do post request
That is not a POST request, AFAICT. You are using Request.Method.GET.
Use following method to post the data to server
public void postDataVolley(Context context,String url,JSONObject sendObj){
try {
RequestQueue queue = Volley.newRequestQueue(context);
JsonObjectRequest jsonObj = new JsonObjectRequest(url,sendObj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Volley", "Volley JSON post" + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Volley", "Volley JSON post" + "That didn't work!");
}
});
queue.add(jsonObj);
}catch(Exception e){
}
}