Iam using Volley library to post json array to RestApi. But i get an error BasicNetwork.performRequest: Unexpected response code 400. I lookfor many articles Volley - Sending a POST request using JSONArrayRequest but not get any solution yet.
Here's my code,
final JSONArray jsonArray = new JSONArray();
List<User> users = UserManager.composeUsers();
jsonArray.put(users);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, "http://192.168.137.1:8080/create", jsonArray, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("Response: ", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error: ", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return String.format("application/json; charset=utf-8");
}
};
queue.add(jsonArrayRequest);
}
In the above code List<User> user return a java object. I want to pass the user object to rest service.
Related
The jason array request code goes like this:
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.GET,url, (JSONArray) null , new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Log.d("Response:", String.valueOf(response.getJSONObject(0)));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Response not recieved", Toast.LENGTH_SHORT).show();
}
});
And I've used a singleton instance of a request queue, to fetch the data,
AppController.getInstance(context.getApplicationContext()).addToRequestQueue(arrayRequest);
I'm using an api service that supplies a bunch of questions (The api generates a url, which returns a collection of JSON Objects, An Array (Just try and Open the url link, the json array will be seen)
But when I run the app, the request is not even getting a response,the progam flow is going into the error listner block.
Can someone explain this behaviour? Is it because the JSON array supplied by the url, has nested arrays? Why?
I tried reading and anlyzing other questions here, which might have the same issue, But i found nothing.
You want to just change JsonArrayRequest to JsonObjectRequest:
Please copy and paste below code:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String category = jsonObject.getString("category");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "Error: " + error.getMessage());
// hide the progress dialog
}
});
AppController.getInstance().addToRequestQueue(jsonObjReq, "TAG");
Follow this link for learn other request: Androidhive
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);
Hello friends I have following JSON Array response from a web service and I want to read all the data row wise from the Database and display on Android Activity.
[{"id":"2","type":"0","title":"Recruitment at ADANI Port, Mundra","date":"2016-07-01"},{"id":"1","type":"1","title":"Training at DAICT, Gandhinager","date":"2016-07-04"}]
I have implemented following code in onCreate() of an Activity using Volley Library, which doesn't show output and to my knowledge it doesn't call onResponse() method.
public void getNews(){
String url = "http://www.ABCDXYZ.net/tponews.php?tponews=1";
Log.e("URL",url);
requestQueue = Volley.newRequestQueue(this);
JsonArrayRequest jor = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Log.e("Resposne", "We have got the response");
JSONObject val = response.getJSONObject(0);
}catch (JSONException e){e.printStackTrace();}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley",error.toString());
}
}
);
requestQueue.add(jor);
}
The output is only URL in Log.e("URL",url); // URL: www.ABCXYZ.net/tponews.php?tponews=1
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){
}
}
I got this error from volley library
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
the error
com.android.volley.ParseError: org.json.JSONException: Value [{"id":"admin","name":"Admin"}] of type org.json.JSONArray cannot be converted to JSONObject
How can I receive the result as string and then I will process it using jackson ?
If you want to receive the result as a string don't use the JSONRequest. Go with the simple Request class.
Your problem is pretty simple the server is giving back a JSONArray with just one element inside.
A JSONArray is not a JSONObject. That's why the parsing is failing.
We Have to use JsonArrayRequest instead of JsonObjectRequest. The code as:
RequestQueue queue = Volley.newRequestQueue(this);
final String url = "http://192.168.88.253/mybazar/get_product_list.php";
// prepare the Request
JsonArrayRequest getRequest = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>()
{
#Override
public void onResponse(JSONArray response) {
// display response
Log.d("Response", response.toString());
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
// add it to the RequestQueue
queue.add(getRequest);
Hope, it's solve the problem.
I noticed that there is class JsonArrayRequest supported by volley so I use this class and the problem solved, I was using JsonObjectRequest
https://android.googlesource.com/platform/frameworks/volley/+/43950676303ff68b23a8b469d6a534ccd1e08cfc/src/com/android/volley/toolbox
Probably the below logic will work for you:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET,
url,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject1 = new JSONObject(response.toString());
JSONArray jsonArray = jsonObject1.getJSONArray("statewise");
Log.d("Json response", "onResponse: "+jsonObject1.toString());
for (int i = 0; i < jsonArray.length; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
//Here you will get your result so can use textview
//to populate the result
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse: "+error);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjectRequest);
}