Volley is sending empty params - android

In my android app, I am sending a volley POST request and it's not working. Rather it is sending empty parameters.
If I enter the url (https://blogurl.com/wp-json/wp/v2/comments?post=20081&author_name=Ozuf&author_email=myemail#my.com&content=This_is_a_sampe_comment) in postman and send a POST request it yields the desired result.
And the code generated by Postman looks like this for JAVA OKHttp:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://blogurl.com/wp-json/wp/v2/comments?post=20081&author_name=Ozuf&author_email=myemail#my.com&content=This_is_a_sampe_comment")
.post(null)
.addHeader("cache-control", "no-cache")
.addHeader("postman-token", "23f2c2587-e9eb-5446-3d73-a1a1a6814683")
.build();
Response response = client.newCall(request).execute();
This is the code I am using to send the POST request:
public void submitComment() {
final String comment = commentContent.getText().toString().trim();
final String name = commentName.getText().toString().trim();
final String email = commentEmail.getText().toString().trim();
Log.d(TAG, "submitComment called");
if (allFieldsAreValid()) {
Log.d(TAG, "All fields are valid");
final String postComment = "https://blogurl.com/wp-json/wp/v2/comments?";
final PostingComment postingComment = PostingComment.newInstance();
postingComment.show(getFragmentManager(), "fragmentDialog");
JsonObjectRequest postDetails = new JsonObjectRequest(Method.POST, postComment, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
parseResponse(response);
postingComment.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse for getPost called");
VolleyLog.d(TAG, "Error: " + error.getMessage());
postingComment.dismiss();
if (sthWrongAlert != null) {
sthWrongAlert.show();
}
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("post", comtUrl);
params.put("author_name", name);
params.put("author_email", email);
params.put("content", comment);
return params;
}
};
int retrytimes = 10;
RetryPolicy policy = new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, retrytimes, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
postDetails.setRetryPolicy(policy);
//Creating requestqueue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding request queue
requestQueue.add(postDetails);
Log.d(TAG, "Data sent is " + comment + name + email);
} else {
Log.d(TAG, "All fields are not valid");
}
}
And Like I said before, the request goes true but the parameters are not sent along with it.
EDIT
After applying djodjo answer
public void submitComment() {
String comment = null;
try {
comment = URLEncoder.encode(commentContent.getText().toString().trim(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String name = null;
try {
name = URLEncoder.encode(commentName.getText().toString().trim(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String email = null;
try {
email = URLEncoder.encode(commentEmail.getText().toString().trim(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.d(TAG, "submitComment called");
if (allFieldsAreValid()) {
Log.d(TAG, "All fields are valid");
final String postComment = "https://blogurl.com/wp-json/wp/v2/comments?post="+comtUrl+"&content="+comment+"&author_name="+name+"&author_email="+email;
final PostingComment postingComment = PostingComment.newInstance();
postingComment.show(getFragmentManager(), "fragmentDialog");
JsonObjectRequest postDetails = new JsonObjectRequest(Method.POST, postComment, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
parseResponse(response);
postingComment.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse for getPost called");
VolleyLog.d(TAG, "Error: " + error.getMessage());
postingComment.dismiss();
if (sthWrongAlert != null) {
sthWrongAlert.show();
}
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
};
int retrytimes = 10;
RetryPolicy policy = new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, retrytimes, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
postDetails.setRetryPolicy(policy);
//Creating requestqueue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding request queue
requestQueue.add(postDetails);
Log.d(TAG, "Data sent is " + comment + name + email);
} else {
Log.d(TAG, "All fields are not valid");
}
}
After applying his solution, that's how my codes looks like. But I am constantly getting error 409.
06-20 19:13:26.405 25586-27084/com.jozuf.blog E/Volley: [6168] BasicNetwork.performRequest: Unexpected response code 409 for https://blog.url/wp-json/wp/v2/comments?post=20081content=Yyggggbbhhgggggg&author_nameRrrauthor_emailgf%40ff.com

After the debugging in chat, the issue found was that it is a POST request but the parameters are still being sent in the request url.
In your case sending a POST response will make the param to go in the body as a multipart form which needs to be fixed. Update you code with below
public void submitComment() {
String comment = null;
try {
comment = URLEncoder.encode(commentContent.getText().toString().trim(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String name = null;
try {
name = URLEncoder.encode(commentName.getText().toString().trim(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String email = null;
try {
email = URLEncoder.encode(commentEmail.getText().toString().trim(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.d(TAG, "submitComment called");
if (allFieldsAreValid()) {
Log.d(TAG, "All fields are valid");
final String postComment = "https://blogurl.com/wp-json/wp/v2/comments?post="+comtUrl+"&content="+comment+"&author_name="+name+"&author_email="+email;
final PostingComment postingComment = PostingComment.newInstance();
postingComment.show(getFragmentManager(), "fragmentDialog");
JsonObjectRequest postDetails = new JsonObjectRequest(Method.POST, postComment, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
parseResponse(response);
postingComment.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse for getPost called");
VolleyLog.d(TAG, "Error: " + error.getMessage());
postingComment.dismiss();
if (sthWrongAlert != null) {
sthWrongAlert.show();
}
}
});
int retrytimes = 10;
RetryPolicy policy = new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, retrytimes, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
postDetails.setRetryPolicy(policy);
//Creating requestqueue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding request queue
requestQueue.add(postDetails);
Log.d(TAG, "Data sent is " + comment + name + email);
} else {
Log.d(TAG, "All fields are not valid");
}
}
The duplicate issue is explained in this thread
Just change the request to have this retry policy and it will work
request.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

getParams() are not called for JsonRequests.
What you can do is just append to
postComment the extra params. for example:
final String comment = URLEncoder.encode(commentContent.getText().toString().trim(), "UTF-8");
final String name = URLEncoder.encode(commentName.getText().toString().trim(), "UTF-8");
final String email = URLEncoder.encode(commentEmail.getText().toString().trim(), "UTF-8");
final String postComment = "https://blogurl.com/wp-json/wp/v2/comments?comment="+comment+"&name="+name+"&email="+email;

You can send the parameters as JSONObject like this:
JSONObject params = new JSONObject("{\"post\":\"" + comtUrl + "\"," +
...
+ "}"
and in JsonObjectRequest you pass it as the third parameter.. you will not need getBodyContentType and getParams anymore

Related

How to solve the problem in login json parsing using volley?

public void userLogin() {
try {
String URL = "http://influence360.in/orezmiapp/index.php/mobile/login";
System.out.println("Arun URL :- " + URL);
final JSONObject jsonBody = new JSONObject();
jsonBody.put("type", "2");
jsonBody.put("email", email);
jsonBody.put("password", password);
final String mRequestBody = jsonBody.toString();
Log.e("JSON String is :- ", " " + mRequestBody);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("LOG_VOLLEY", response);
try {
Toast.makeText(activity, "loginactivity entered", Toast.LENGTH_LONG).show();
JSONObject jsonObject = new JSONObject(response);
int status = jsonObject.getInt("status");
Toast.makeText(activity, status, Toast.LENGTH_LONG).show();
if (status == 1000) {
JSONObject data = jsonBody.getJSONObject("data");
//sessionManager.setUserid(data.getString("Cust_id"));
// sessionManager.setBirthday(data.getString("Dob"));
sessionManager.setUserfirstname(data.getString("Cust_Name"));
startActivity(new Intent(LoginScreen.this, Profile.class));
finish();
} else {
Toast.makeText(activity, "Hello", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(activity, e.toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG_VOLLEY", error.toString());
}
})
{
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
return headers;
}
#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
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
Log.e("Response String : -", " " + responseString);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
RequestQueue requestQueue = Volley.newRequestQueue(activity);
requestQueue.add(stringRequest);
stringRequest.setRetryPolicy(new
DefaultRetryPolicy(60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
I got the error
value of type 200 org.json.Integer cant be converted into JSONObject. Please help me to solve this. I didnt get any solution regarding this. Thankyou in advance.Please help me out.I will be highly obliged if anybody give the solution.Thank you in advance. If anybody has the solution please give me that.

Volley delete request with body data not working

hello everyone im facing a problem with volley delete request .
i working on task in user add or remove some contacts by it's id .
im using volley library for it.
API is tested with postman and working fine.
private void AddContactInList(final Contacts contacts,int RequestMethod) {
JSONArray ContactArray = new JSONArray();
ContactArray.put(StoredContactid);
final String jsonStr = ContactArray.toString();
String URl = OrganizationModel.getApiBaseUrl() + getOrgId() + "/lists/" + contacts.getId()+"/contacts";
Log.i(TAG,URl);
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonObjectRequest jsonArrayRequest = new JsonObjectRequest(RequestMethod,URl,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG,response.toString());
try {
JSONArray mJSONArray = response.getJSONArray("contactIds");
contacts.setCode(String.valueOf(mJSONArray.length()));
long time = System.currentTimeMillis();
sqliteDataBaseHelper.changeContactUpdatedON(StoredContactid, String.valueOf(time));
sqliteDataBaseHelper.updateListContactsAndLength(contacts.getId(), mJSONArray.toString(), (mJSONArray.length()));
dataAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG,error.toString());
String json = null;
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 400:
case 405:
json = new String(response.data);
json = dataHelper.trimMessage(json, "message");
if (json != null) dataHelper.displayMessage(json);
break;
}
}
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() {
try {
return jsonStr == null ? null : jsonStr.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
jsonStr, "utf-8");
return null;
}
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("Authorization", "Basic " + GetApiAccess());
return headers;
}
};
jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(
9000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonArrayRequest);
}
In my SQLite Database , the below code is working. Hope it may help you..
public void DeleteData(){
btnDltData.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer deleteRows = myDB.deleteData(editId.getText().toString());
if(deleteRows > 0)
Toast.makeText(MainActivity.this, "Task Clear..", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "Task not Clear..", Toast.LENGTH_SHORT).show();
editId.setText("");
}
}
);
}
http://www.itsalif.info/content/android-volley-tutorial-http-get-post-put
try this, if problem didnt solve yet

need first volley request response to make json object for second request

I have a big problem with volley request sequence and making json array out of first request response for second request.
this is the code :
JSONObject imageAddedResponse = new JSONObject();
JSONArray imagesAddedResponse = new JSONArray();
public void postImageData(Context applicationContext, String title, String note, ArrayList<ContentData> mImages, String videoPath, final Listeners.APIPostDataListener listener) {
//Instantiate the RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(applicationContext);
Settings settings = new Settings(applicationContext);
String selectedURL = settings.getChosenUrl();
final String token = settings.getTokenKey();
String url = "http://" + selectedURL + "/databox/api/v1/upload/files";
HashMap<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer " + token);
params.put("Content-Disposition", "form-data" + "; charset=utf-8");
//POST data to CMS to get JSONObject back
for (int i = 0; i < mImages.size(); i++) {
String path = String.valueOf(mImages.get(i).getPath());
File file = new File(path);
MultipartRequest request = new MultipartRequest(url, file, Response.class, params, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (listener != null) {
listener.onAPIPostData(String.valueOf(response), true);
}
if (response != null || response != "") {
try {
imageAddedResponse = new JSONObject(response);
JSONObject jsonArraydata = imageAddedResponse.getJSONObject("data");
JSONArray jsonArrayImages = jsonArraydata.getJSONArray("images");
imagesAddedResponse.put(jsonArrayImages);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley Request Error", error.toString());
if (listener != null) {
listener.onAPIPostData("", false);
}
}
});
requestQueue.add(request);
}
//POST request to add entity to CMS
JSONObject jsonimages = new JSONObject();
JSONArray jsonArrayimages = new JSONArray();
for (int i = 0 ; i < imagesAddedResponse.length() ; i++){
try {
JSONObject getObjectValues = imagesAddedResponse.getJSONObject(i);
jsonimages.put("id",getObjectValues.getString("id"));
jsonimages.put("src",getObjectValues.getString("src"));
jsonimages.put("size",getObjectValues.getString("size"));
jsonimages.put("baseName",getObjectValues.getString("baseName"));
jsonimages.put("type",getObjectValues.getString("type"));
jsonimages.put("db_languages_id", "1");
jsonimages.put("title",String.valueOf(mImages.get(i).getTitle()));
} catch (JSONException e) {
e.printStackTrace();
}
}
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONObject finalobject = new JSONObject();
try {
json.put("title", title);
json.put("description", note);
json.put("db_languages_id", "1");
json.put("db_user_id", "3");
jsonArray.put(json);
finalobject.put("data", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
String urlFinal = "http://" + selectedURL + "/databox/api/v1/1/entity";
JsonObjectRequest postRequest = new JsonObjectRequest(urlFinal, json, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// response
if (listener != null) {
listener.onAPIPostData(String.valueOf(response), true);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
if (listener != null) {
listener.onAPIPostData("", false);
}
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer " + token);
params.put("Content-Type", "application/json; charset=utf-8");
return params;
}
};
postRequest.setShouldCache(false);
requestQueue.add(postRequest);
}
first request post to CMS and get some information for images posted and then I need to add those information to next post to make entity based on response I got back from first post request.
int totalSuccesfulImagePost = 0; //this variable increment when each succesful response from multipart-request
public void postImageData(Context applicationContext, String title, String note, ArrayList<ContentData> mImages, String videoPath, final Listeners.APIPostDataListener listener) {
//Instantiate the RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(applicationContext);
Settings settings = new Settings(applicationContext);
String selectedURL = settings.getChosenUrl();
final String token = settings.getTokenKey();
String url = "http://" + selectedURL + "/databox/api/v1/upload/files";
HashMap<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer " + token);
params.put("Content-Disposition", "form-data" + "; charset=utf-8");
//POST data to CMS to get JSONObject back
for (int i = 0; i < mImages.size(); i++) {
String path = String.valueOf(mImages.get(i).getPath());
File file = new File(path);
MultipartRequest request = new MultipartRequest(url, file, Response.class, params, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (listener != null) {
listener.onAPIPostData(String.valueOf(response), true);
}
if (response != null || response != "") {
try {
imageAddedResponse = new JSONObject(response);
JSONObject jsonArraydata = imageAddedResponse.getJSONObject("data");
JSONArray jsonArrayImages = jsonArraydata.getJSONArray("images");
imagesAddedResponse.put(jsonArrayImages.getJSONObject(0));
totalSuccesfulImagePost++; //here we increase the count
postRequest(token); //call this method and check wheather all the image uploaded or not
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley Request Error", error.toString());
if (listener != null) {
listener.onAPIPostData("", false);
}
}
});
requestQueue.add(request);
}
}
//make this as seperate method and call when all multipart-request call succesful
public void postRequest(String token){
if(totalSuccesfulImagePost != mImages.size()) {
//this means not all the images posted yet, hence return the method
return;
}
//POST request to add entity to CMS
JSONObject jsonimages = new JSONObject();
JSONArray jsonArrayimages = new JSONArray();
for (int i = 0 ; i < imagesAddedResponse.length() ; i++){
try {
JSONObject getObjectValues = imagesAddedResponse.getJSONObject(i);
jsonimages.put("id",getObjectValues.getString("id"));
jsonimages.put("src",getObjectValues.getString("src"));
jsonimages.put("size",getObjectValues.getString("size"));
jsonimages.put("baseName",getObjectValues.getString("baseName"));
jsonimages.put("type",getObjectValues.getString("type"));
jsonimages.put("db_languages_id", "1");
jsonimages.put("title",String.valueOf(mImages.get(i).getTitle()));
} catch (JSONException e) {
e.printStackTrace();
}
}
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONObject finalobject = new JSONObject();
try {
json.put("title", title);
json.put("description", note);
json.put("db_languages_id", "1");
json.put("db_user_id", "3");
jsonArray.put(json);
finalobject.put("data", jsonArray);
} catch (JSONException e) {
e.printStackTrace();.getJSONObject(0)
}
String urlFinal = "http://" + selectedURL + "/databox/api/v1/1/entity";
JsonObjectRequest postRequest = new JsonObjectRequest(urlFinal, json, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// response
if (listener != null) {
listener.onAPIPostData(String.valueOf(response), true);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
if (listener != null) {
listener.onAPIPostData("", false);
}
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer " + token);
params.put("Content-Type", "application/json; charset=utf-8");
return params;
}
};
postRequest.setShouldCache(false);
requestQueue.add(postRequest);
}
updated your code. Hope this may help you.
I've created new method for JsonObjectRequest with the name postRequest();
totalSuccesfulImagePost variable holds the no. of succesfull response for image upload
new method postRequest() calls at each multipart-request response
postRequest() methods check if not all response process yet than skip the 2nd api call
Also see how fb do this batch request https://developers.facebook.com/docs/android/graph/ -> Batch Reqest
Note -
Ive increment the variable totalSuccesfulImagePost and handle in each response, although you need to Response.ErrorListener()
Although you can go with the ThreadPoolExecutor option where each thread is created to handle each multipart-request upload and after all thread execution , call the method postRequest()
Work-around using ThreadPoolExecutor
a) Create ThreadPoolExecutor & initialize min/max pool size
b) Asign each mulitpart-request to upload image to each thread
c) Add all thread (contain image upload multipart-request) to ThreadPoolExecutor
d) Execute pool
e) call postRequest() method when ThreadPoolExecutor is empty i.e. this means all the thread execution is done and ready to call postRequest()
it is possible using Priority Of each Request.
private Priority priority = Priority.HIGH;
StringRequest strReq = new StringRequest(Method.GET,
Const.URL_STRING_REQ, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
}) {
#Override
public Priority getPriority() {
return priority;
}
};
MyApplication.getInstance().addToRequestQueue(strReq);

Volley error response is null in android?

I have used the volley library to get the API response. Initially when am calling the API the error response is showing exactly from the server. but when i again call the API means i am getting error response is null.
Kindly help me to do this.
Here is my code
public void requestString(final String requestName,
final String webserviceUrl,
final Map<Object, Object> requestParams, final int webMethod,
final boolean getCache) {
LogUtils.i("Sending Request", webserviceUrl);
StringRequest stringRequest = new StringRequest(webMethod,
webserviceUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
LogUtils.i("Response", response);
mRequestCompletedListener.onRequestCompleted(
requestName, true, response, null);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String errorResponse = null;
if (getCache) {
final Cache cache = AppController.getInstance()
.getRequestQueue().getCache();
final Entry entry = cache.get(webserviceUrl);
if (entry.data != null) {
try {
errorResponse = new String(entry.data, "UTF-8");
mRequestCompletedListener
.onRequestCompleted(requestName,
true, errorResponse, null);
return;
} catch (UnsupportedEncodingException e) {
LogUtils.e(TAG, e);
}
} else {
LogUtils.e(TAG, requestName
+ " Cache does not exist");
}
}
try {
VolleyError responseError = new VolleyError(
new String(error.networkResponse.data));
LogUtils.i("ErrorResponse", responseError.getMessage());
try {
if (responseError != null) {
final JSONObject responseJson = new JSONObject(responseError.getMessage());
// Show Alert Information
errorResponse = responseJson.getString(AppConstants.MESSAGE);
}
} catch (Exception e) {
errorResponse = "Unknown";
}
} catch (Exception e) {
LogUtils.e(TAG, e);
}
mRequestCompletedListener.onRequestCompleted(
requestName, false, null,
errorResponse);
}
})
stringRequest.setTag(requestName);
// Adding String request to request queue
AppController.getInstance().addToRequestQueue(stringRequest);
}
Here am passing the Params:
AppController.getInstance().requestApi(mVolleyRequest, REQUEST_NAME, PATH
+ API, Request.Method.POST, HTTP_POST, Request.Priority.HIGH
, false, out.toString().trim(), true);

BasicNetwork.performRequest: Unexpected response code 400

I have a big problem. Normally, i did not receive this error anytime. But now i am receiving. How can solve that problem? I research and i learn i need create custom header with getBodyContentType(). But that is not solving for me..
public void getToken(final Activity activity, final String paramUsername, final String paramPassword) {
String tag_json_obj = "getToken";
SharedComponent.pDialog = new ProgressDialog(activity);
SharedComponent.pDialog.setMessage(context.getString(R.string.controlYourInfo));
SharedComponent.pDialog.setCancelable(false);
SharedComponent.pDialog.show();
JSONObject params = new JSONObject();
try {
params.put("username", paramUsername);
params.put("password", paramPassword);
params.put("grant_type", "password");
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
WebUrls.getToken, params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Log.d(TAG, response.toString());
SharedComponent.pDialog.hide();
try {
if (response.toString().contains("error")) {
error = response.getString("error");
error_description = response.getString("error_description");
Toast.makeText(context, error_description, Toast.LENGTH_LONG).show();
} else {
access_token = response.getString("access_token");
token_type = response.getString("token_type");
expires_in = response.getInt("expires_in");
SharedComponent.sharedEditor.putString("TOKEN", "Bearer " + access_token);
SharedComponent.sharedEditor.putString("LOGGED", "LOGGED");
SharedComponent.sharedEditor.commit();
Log.e("TOKEN", "Bearer " + access_token);
Intent intent = new Intent(activity, MainScreen.class);
context.startActivity(intent);
((Activity) context).finish();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context,
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// VolleyLog.d(TAG, "Error: " + error.getMessage());
SharedComponent.pDialog.hide();
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
headers.put("Content-Type", getBodyContentType());
return headers;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}

Categories

Resources