Volley Parse Error, Handling String in a Json Object Request - java

I'm using JsonObjectRequest because the Api Response is in JSON Format but in some cases, the response can be just a String. So if the API returns a String, It will generate a Volley Parse Error. So I'm just wondering if there is any solution for handlings a string in JsonObjectRequest without having to use StringRequest or CustomRequest.
Here's my Code:
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url,null,
(Response.Listener<JSONObject>) response -> {
JSONObject jsonObject = response;
Map map = new Gson().fromJson(String.valueOf(jsonObject),HashMap.class);
},
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
try {
String responseBody = new String(error.networkResponse.data, "utf-8");
Toast.makeText(mContext, responseBody, Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(mContext, "Something went wrong! ", Toast.LENGTH_SHORT).show();
}
}
}
) {
public byte[] getBody() {
return new JSONObject(params).toString().getBytes();
}
public String getBodyContentType() {
return "application/json";
}
};
Volley.newRequestQueue(mContext).add(request);

Related

How to send JSONArray as params and recieve JSONObject as response

I have an API that takes a JSONArray as params and it gives a JSONObject as a response. The API is working fine but giving an error
com.android.volley.ParseError: org.json.JSONException: End of input at character 0 of
at com.android.volley.toolbox.JsonArrayRequest.parseNetworkResponse
as I receive the response.
JsonArrayRequest volleyRequest= new JsonArrayRequest(Request.Method.POST, url,
params, res -> {
try {
Log.d("TAG", "PostApiMethod: "+res);
} catch (JSONException e) {
Log.e("TAG", "PostApiMethod: ", e);
}
}, error -> {
Log.e(TAG, "PostApiMethod: ", error);
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
};
VolleySingleton.getInstance(context).addToRequestQueue(volleyRequest);
Is there any way to do this while using Volley.
you can use StringRequest and convert JSONArray to String as parameters and get result as String and map string to JSONObject like this code
JSONArray jsonBody=new JSONArray();
try {
/// add jSONObject inside JSONArray as example
JSONObject jsonObject=new JSONObject();
jsonObject.put("id",1);
jsonObject.put("name","test");
jsonBody.put(jsonObject);
} catch (Exception e) {
e.printStackTrace();
}
final String requestBody = jsonBody.toString();
StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
textView.setText(response.toString());
try {
JSONObject object=new JSONObject(response);
// do every thing using json object
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error",error.toString());
}
}){
#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) {
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));
}
};
I recommended using retrofit library instead of Volley

How to implement a post method for Imgflip API

I am trying to create an app on android studio and im new to this IDE and language. I managed to implement the GET method for Imflip api, but im stuck on the POST method. I would like to return an Meme with a caption added by the user.
Im using Android Studio 3.4.1. I've tried the code attached. For testing purposes, i've hardcoded the username, password, and two captions. Also, when i call POST() I pass the id 61579 as a parameter. I've tried finding he value for the response but it says that its "200"...
What i need is a url for the created meme.
Hope anyone can help.
Thanks in Advance.
private void POST(String memeID) {
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "https://api.imgflip.com/caption_image";
JSONObject jsonBody = new JSONObject();
jsonBody.put("template_id", memeID);
jsonBody.put("username", "Meme_Genie");
jsonBody.put("password", "Password");
jsonBody.put("text0", "Hello");
jsonBody.put("text1", "World");
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#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) {
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);
} catch (JSONException e) {
e.printStackTrace();
}
}
Switching from encode = "json" to encode = "form"
Or switching your body to BodySerializationMethod.UrlEncoded will work

Android Volley POST - JSON Encoding in body

I'm using Volley Android for POST some data to a Restful Api endpoint, using postman it works great body data in raw and application/json e.g:
{
"operation": "someaction",
"key": "pk_test_fssdfsdfjkhkjsdhf84334",
"token": "tk_test_432332sdxxaJJJJHHHshhsas",
"ssids":[[{
"mac":"34:15:13:d4:59:f1" //<--this is important here, it's mac addr
}]] //<-- yup, with double double [[ ... ]]
}
It works using POSTMAN and returns
The issue starts when I use volley in the code below:
public void getBleeCardData(Response.Listener<String> response, final String ssidsdata, final ProgressDialog pd)throws JSONException {
String url = "https://www......com/api/something.do";
JSONObject jsonBody = new JSONObject();
jsonBody.put("operation", "something");
jsonBody.put("key", "pk_try_oqiwFHFKjkj4XMrh");
jsonBody.put("token", "tk_tkn_erwweelWgH4olfk2");
jsonBody.put("ssids", ssidsdata.toLowerCase());
final String mRequestBody = jsonBody.toString();
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest postRequest = new StringRequest(Request.Method.POST, url,new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR", "error => " + error.toString());
}
}
) {
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
return null;
}
}
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
};
queue.add(postRequest.setRetryPolicy(new DefaultRetryPolicy(30000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT))); }
I need help with the encoding, using Volley the data sent like:
{"operation":"dataMachines","key":"pk_test_6pRNAHGGoqiwFHFKjkj4XMrh","token":"tk_test_ZQokik736473jklWgH4olfk2","ssids":"[[{\"mac\":\"34:15:13:d4:59:f1\"}]]"}
Why is sending this node like "ssids":"[[{\"mac\":\"34:15:13:d4:59:f1\"}]]"}like this?, What about the "\", some special encoding to remove it?
Is possible change the encoding to prevent those "\"?
Create a JsonObjectRequest
JSONObject jsonBody = new JSONObject();
jsonBody.put("operation", "something");
jsonBody.put("key", "pk_try_oqiwFHFKjkj4XMrh");
jsonBody.put("token", "tk_tkn_erwweelWgH4olfk2");
jsonBody.put("ssids", ssidsdata.toLowerCase());
JsonObjectRequest jobReq = new JsonObjectRequest(Request.Method.POST, url, jsonBody,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
//Log.d("Responses", jsonObject.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Log.e("responses", volleyError.toString());
}
});
if you are sending JSONArray then instead of JsonObjectRequest use JsonArrayRequest
JSONObject obmacAdd=new JSONObject();
JSONArray array=new JSONArray();
obmacAdd.put("mac","34:15:13:d4:59:f1");
array.put(obmacAdd.toString());
now
jsonBody.put("ssids", array.toString());
According to the android code,the below expects a string,while you are parsing an object:
jsonBody.put("ssids", ssidsdata.toLowerCase());
You could make the ssid seperately then add it in the json body like this:
JSONObject ssid= new JSONObject();
ssid.put("mac":"34:15:13:d4:59:f1");
ssid.put("key2","Value2");
The add the ssid object into your Json object to send:
JSONObject jsonBody = new JSONObject();
jsonBody.put("operation", "something");
jsonBody.put("key", "pk_try_oqiwFHFKjkj4XMrh");
jsonBody.put("token", "tk_tkn_erwweelWgH4olfk2");
jsonBody.put("ssids", ssid);
As well explaned here: Pass an object containing key value pairs, as a value to a hashmap in Java/Android

Send JSON Object in POST request from Android Volley receive java restful webservices

I want small example to send JSON object in POST request from android volley and it has to receive Java Restful Webservices
You can use the following working sample code. Hope this helps!
...
try {
RequestQueue queue = Volley.newRequestQueue(this);
jsonBody = new JSONObject();
jsonBody.put("Title", "VolleyApp Android Demo");
jsonBody.put("Author", "BNK");
jsonBody.put("Date", "2015/08/26");
requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(1, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
textView.setText(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
textView.setText(error.toString());
}
}) {
#Override
public String getBodyContentType() {
return String.format("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;
}
}
};
queue.addToRequestQueue(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
Moreover, can you clarify what does it has to receive Java Restful Webservices mean? My above request receives String value.

How to do a Volley PUT to a drupal table

I'm attempting to do a PUT in x-www-form-urlencoded to a drupal table with Volley from my Android app. I'm try to send a 'type' and 'value', in the params and I get a 500 error. A basic StringRequest returns 404.
Here's my latest code. I've only found one or two entries that touch on the Volley Put. Any help would be appreciated. Have a great day.
private void postTestAnswerResult(String id, String answerResult) {
StringRequest req = null;
requestQueue = Volley.newRequestQueue(this);
final String baseURL = "http://blah.blah.com/api/answer/";
String URL = baseURL + id;
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
params.put("type", answerResult);
req = new StringRequest(Request.Method.PUT, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.v("Response:%n %s", response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
try {
String responseBody = new String(
volleyError.networkResponse.data, "utf-8");
JSONObject jsonObject = new JSONObject(responseBody);
} catch (JSONException e) {
// Handle a malformed json response
} catch (UnsupportedEncodingException error) {
}
}
}
);
requestQueue.add(req);
}
In case you are still having problems with this, as #Meier points out in a comment above, you are not using the params variable, or rather you aren't using it correctly. The data doesn't get sent to the server, and the server is probably expecting the data resulting in the 500 error.
You need to override the getParams method of the StringRequest call in order to send the data. So, the following would be closer to getting the job done:
private void postTestAnswerResult(String id, String answerResult) {
StringRequest req = null;
requestQueue = Volley.newRequestQueue(this);
final String baseURL = "http://blah.blah.com/api/answer/";
String URL = baseURL + id;
req = new StringRequest(Request.Method.PUT, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.v("Response:%n %s", response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
try {
String responseBody = new String(
volleyError.networkResponse.data, "utf-8");
JSONObject jsonObject = new JSONObject(responseBody);
} catch (JSONException e) {
// Handle a malformed json response
} catch (UnsupportedEncodingException error) {
}
}
}
) {
#Override
protected Map<String, String> getParams()
{
HashMap<String, String> params = new HashMap<String, String>();
// params.put("Content-Type","application/x-www-form-urlencoded"); This shouldn't be here. This is a HTTP header. If you want to specify header you should also override getHeaders.
params.put("type", answerResult);
return params;
}
};
requestQueue.add(req);
Browser don't ignore 500 errors. They very often show up as ugly messages in the browser window.

Categories

Resources