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);
Related
This is my Java code:
public void imageUpload(final Context context, final String imagePath) {
final String requestBody;
JSONObject jsonUser = null;
JSONObject jsonAddress = null;
JSONObject jsonDriver = null;
JSONObject jsonImage = null;
String URL = SIGN_UP;
final String ConvertImage;
jsonUser = new JSONObject();
try {
jsonUser.put("first_name", "ABC");
jsonUser.put("last_name", "XYZ");
jsonUser.put("email", "yash#gmail.com");
jsonUser.put("phone", "9999900000");
jsonUser.put("password", "Yash#123");
jsonAddress = new JSONObject();
jsonAddress.put("address", "MUMBAI");
jsonAddress.put("city", "MUMBAI");
jsonAddress.put("state", "MH");
jsonAddress.put("zip", "369852");
jsonDriver = new JSONObject();
jsonDriver.put("middle_name", "GG");
jsonDriver.put("vehicle_type", "CAR");
jsonDriver.put("car_plate_number", "123456");
jsonDriver.put("car_brand", "BMW");
jsonDriver.put("making_year", "2011");
jsonDriver.put("date_of_birth", "2019-06-01");
jsonDriver.put("license_number", "12346579");
jsonDriver.put("license_state", "MH");
jsonDriver.put("social_security_number", "123456");
JSONObject jsonObjectFinal = new JSONObject();
jsonObjectFinal.put("user", jsonUser);
jsonObjectFinal.put("address", jsonAddress);
jsonObjectFinal.put("driver", jsonDriver);
} catch (JSONException e) {
e.printStackTrace();
}
SimpleMultiPartRequest smr = new SimpleMultiPartRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
try {
JSONObject jObj = new JSONObject(response);
String message = jObj.getString("message");
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "" + error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
/*params.put("user", jsonUser + "");
params.put("address", jsonAddress + "");
params.put("driver", jsonDriver + "");
Log.d("Param", "" + params + "***");*/
return params;
}
};
smr.addFile("license_image", imagePath);
smr.addMultipartParam("user", "text/plain", jsonUser + "");
smr.addMultipartParam("address", "text/plain", jsonAddress + "");
smr.addMultipartParam("driver", "text/plain", jsonDriver + "");
Log.d("Param", "" + smr.getMultipartParams() + "***");
MySingleton.getInstance(context).addToRequestQueue(smr);
}
The server shows:
data:->
[Object: null prototype] {
address:
'{"address":"SURAT","city":"SURAT","state":"GUJARAT","zip":"369852"}',
driver:
'{"middle_name":"GG","vehicle_type":"CAR","car_plate_number":"123456","car_brand":"BMW","making_year":"2011","date_of_birth":"2019-06-01","license_number":"12346579","license_state":"MH","social_security_number":"123456"}',
user:
'{"first_name":"YASH","last_name":"PANCHAL","email":"yash#gmail.com","phone":"8460277210","password":"Yash#123"}' }
files:-> [ { fieldname: 'license_image',
originalname: '1559197608373.jpg',
encoding: 'binary',
mimetype: 'application/octet-stream',
destination: 'C:\\Users\\Admin\\AppData\\Local\\Temp',
filename: 'license_image-m6i0vcx0-1559197611770.octet-stream',
path:
'C:\\Users\\Admin\\AppData\\Local\\Temp\\license_image-m6i0vcx0-1559197611770.octet-stream',
size: 53156 } ]
The files are sent perfectly but the JSON object is parsed as String, I want to send data like:
{
user:{
'first_name': 'yash',
'last_name': 'panchal'
},
address:{
...
},
driver:{
...
},
licence_image: [file]
}
In Android I have to pass request in JSON object or array including files.
If I try to parse the image via bitmap, the server returns undefined and if I try with pas as String it's working fine but when passing JSON data as above it results in sending object data as a single String.
Have a look at this multipart request with parameter's to a particular server and parsing its response as json :
private void saveProfileAccount() {
// loading or check internet connection or something...
// ... then
String url = "http://www.angga-ari.com/api/something/awesome";
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
String resultResponse = new String(response.data);
try {
JSONObject result = new JSONObject(resultResponse);
String status = result.getString("status");
String message = result.getString("message");
if (status.equals(Constant.REQUEST_SUCCESS)) {
// tell everybody you have succed upload image and post strings
Log.i("Messsage", message);
} else {
Log.i("Unexpected", message);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
String errorMessage = "Unknown error";
if (networkResponse == null) {
if (error.getClass().equals(TimeoutError.class)) {
errorMessage = "Request timeout";
} else if (error.getClass().equals(NoConnectionError.class)) {
errorMessage = "Failed to connect server";
}
} else {
String result = new String(networkResponse.data);
try {
JSONObject response = new JSONObject(result);
String status = response.getString("status");
String message = response.getString("message");
Log.e("Error Status", status);
Log.e("Error Message", message);
if (networkResponse.statusCode == 404) {
errorMessage = "Resource not found";
} else if (networkResponse.statusCode == 401) {
errorMessage = message+" Please login again";
} else if (networkResponse.statusCode == 400) {
errorMessage = message+ " Check your inputs";
} else if (networkResponse.statusCode == 500) {
errorMessage = message+" Something is getting wrong";
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.i("Error", errorMessage);
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("api_token", "gh659gjhvdyudo973823tt9gvjf7i6ric75r76");
params.put("name", mNameInput.getText().toString());
params.put("location", mLocationInput.getText().toString());
params.put("about", mAvatarInput.getText().toString());
params.put("contact", mContactInput.getText().toString());
return params;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
// file name could found file base or direct access from real path
// for now just get bitmap data from ImageView
params.put("avatar", new DataPart("file_avatar.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mAvatarImage.getDrawable()), "image/jpeg"));
params.put("cover", new DataPart("file_cover.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mCoverImage.getDrawable()), "image/jpeg"));
return params;
}
};
VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);
}
This project used to work successfully before. After we changed URL from web service that don't parse data. We changed URL bus/search instead of bus.
This is where I send request and it run successfully with new URL. But this state is working and show this fault.
catch (JSONException e) {
Log.e("search" + owner + "VoyagesErr1", e.toString());
e.printStackTrace();
}
error: e: "org.json.JSONException:No value for status
Voyage.java
private void sendRequest(final String owner, final Map<String, String> header) {
//url = "http://12.1.1.12:1337/";
StringRequest stringRequest = new StringRequest(Request.Method.POST, MyConstants.URL + owner,
new Response.Listener<String>() {
#Override
// servisten 200 olarak bir veri alındığında onResponse içine düşüyor.
public void onResponse(String response) {
// Log.e("AAAA" + owner, response);
try {
JSONObject object = new JSONObject(response);
if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_NOTAVAILABLE)) {
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_NOTAVAILABLE);
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_SUCCESS)) {
JSONArray result = object.getJSONArray(MyConstants.SERVICE_RESULT);
JSONArray resultGoing = result.getJSONObject(0).getJSONArray("going");
if (has_return) {
JSONArray resultReturn = result.getJSONObject(1).getJSONArray("round");
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_RETURN, resultReturn);
}
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_GOING, resultGoing);
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_FAİLURE)) {
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_SERVER);
}
} catch (JSONException e) {
Log.e("search" + owner + "VoyagesErr1", e.toString());
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("AAAA" + owner, String.valueOf(error.getCause()));
sendVoyagesErrorBroadcast(owner, getErrorType(error));
}
It don't receive in this class.
MyBaseVoyageFragment.java
String broadcastTAG = BROADCAST_TAG + owner + String.valueOf(direction);
if (intent != null) { // put the receiving data on intent
Log.e("received", intent.getAction()); // succesfull action
String intentAction = intent.getAction();
if (intentAction.equals(broadcastTAG)) {
parseIntentDataAndLoadVoyagesAdapter = new ParseIntentDataAndLoadVoyagesAdapter(intent);
parseIntentDataAndLoadVoyagesAdapter.execute(""); // asenkron görevi çalıştır.
//loadVoyagesToAdapter();
} else if (intentAction.equals(BROADCAST_TAG + owner + "Error")) {
showLoadingDialog(false);
setErrorView(intent.getIntExtra("data", 0));
}
}
I want to send and receive data from server. For this I've used Volley. The code is in below. Volley can receive the data in Json format. The Server can send and receive data in Json format. How do I convert this Json data into a user readable JAVA format ?? There are about 10 methods in other class. The below class contains the methods for network calls and also interacts with the MainActivity.
public class Api_Volley {
String data;
String flag;
public void my_volley_post (String url , JSONObject jsonObject , final Context context ) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url , jsonObject , new Response.Listener(){
#Override
public void onResponse(Object response) {
String flag = response.toString();
Toast.makeText( context , flag , Toast.LENGTH_LONG ).show();
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context , "Wrong" , Toast.LENGTH_LONG).show();
error.printStackTrace();
}
});
ApiVolleySingeltonClass.getInstance(context).addToRequestque(jsonObjectRequest);
}
}
Methods in another class:
public void showAllOrderByUserId() {
try {
data_args.put("userId", 2);
} catch (JSONException e) {
e.printStackTrace();
}
try {
data_action.put("action", "showAllOrderByUserId");
data_action.put("args", data_args);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
route = "/order";
new Api_Volley().my_volley_post(addUserUrl + route, data_action, context);
}
Your can use json data like
{"userNodes":[{"id":"1","name":"Enamul Haque"}]}
You can use volley like bellow
private void doLoginAction() {
String url_login = "http://www.lineitopkal.com/android/login.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url_login,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//pDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray loginNodes = jsonObject.getJSONArray("userNodes");
for (int i = 0; i < loginNodes.length(); i++) {
JSONObject jo = loginNodes.getJSONObject(i);
String id = jo.getString("id");
Log.e("id ::",id);
String name = jo.getString("name");
Log.e("name ::",name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
try {
if (error instanceof TimeoutError ) {
//Time out error
}else if(error instanceof NoConnectionError){
//net work error
} else if (error instanceof AuthFailureError) {
//error
} else if (error instanceof ServerError) {
//Erroor
} else if (error instanceof NetworkError) {
//Error
} else if (error instanceof ParseError) {
//Error
}else{
//Error
}
//End
} catch (Exception e) {
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
//Post parameter like bellow
params.put("uname", "era#gmail.com");
params.put("pass", "123456");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Create your Response format like this
public class Post {
long id;
Date dateCreated;
String title;
String author;
String url;
String body;
}
After making request like below
public void my_volley_post (String url , JSONObject jsonObject , final Context context ) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url , jsonObject , new Response.Listener(){
#Override
public void onResponse(String response) {
GsonBuilder gsonBuilder = new GsonBuilder();
gson = gsonBuilder.create();
// This will be your Entity
Post post = gson.fromJson(response, Post.class));
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context , "Wrong" , Toast.LENGTH_LONG).show();
error.printStackTrace();
}
});
ApiVolleySingeltonClass.getInstance(context).addToRequestque(jsonObjectRequest);
}
You have to parse JSON and have to show according to need:
By this you can use GSON (Its easy)
Use this Site to convert JSON to pojo classes.
Click here
These are the References site you can use and implement :
http://www.vogella.com/tutorials/JavaLibrary-Gson/article.html
https://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
https://kylewbanks.com/blog/tutorial-parsing-json-on-android-using-gson-and-volley
I have an API call with below details
URL: http://pankajservers.in/api/v1/AuthenticateUser with Input params
below
EmailAddress and Password
if I type wrong credentials, I get below JSON response with Status Code : 403
{"Status":false,"Message":"Invalid Credentials. 5 attempts left.","Data":null}
Below is the Error Response Code.
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
if (null != error.networkResponse)
{
Log.d(TAG + ": ", "Error Response code: " + error.networkResponse.statusCode);
}
}
});
Is there any way to get JSON response in this code block?
I tried this post: Volley handle onErrorResponse
But it seems it never execute parseNetworkError
To print the Error on that block you just need to obtain the Response bytes:
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null && networkResponse.data != null) {
String jsonError = new String(networkResponse.data);
// Print Error!
}
You can create custom request like this:
public class BaseRequest extends Request {
private static final String TAG = BaseRequest.class.getSimpleName();
private final Gson gson = new Gson();
private final Response.Listener listener;
public BaseRequest(String url, Response.Listener responseListener, Response.ErrorListener listener) {
super(Request.Method.GET, url, listener);
Log.e(TAG, "Requesting url : " + url);
this.listener = responseListener;
}
public BaseRequest(int method, String url, Response.Listener responseListener, Response.ErrorListener listener) {
super(method, url, listener);
Log.e(TAG, "Requesting url : " + url);
this.listener = responseListener;
}
#Override
public Response parseNetworkResponse(NetworkResponse response) {
try {
String json = null;
json = new String(
response.data,
HttpHeaderParser.parseCharset(response.headers));
JSONObject result = new JSONObject(json);
if (!result.getBoolean("Status"))
return Response.success(
result.get("Data"),
HttpHeaderParser.parseCacheHeaders(response));
else
return Response.error(new VolleyError(result.getString("Message")));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
} catch (JSONException e) {
return Response.error(new ParseError(e));
}
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
return volleyError;
}
#Override
protected void deliverResponse(Object response) {
listener.onResponse(response);
}
}
and make request:
BaseRequest baseRequest = new BaseRequest(Request.Method.POST, url, new Response.Listener() {
#Override
public void onResponse(Object response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error : " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
//Your parameters
return params;
}
};
queue.add(baseRequest);
You can cast an error response to a Json Object
JSONObject jsonObject = new JSONObject();
JsonObjectRequest JO = new JsonObjectRequest(Request.Method.POST,"URL String Here",jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Your Logic
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
try {
JSONObject JO = new JSONObject(error.toString());
}catch (JSONException e){
e.printStackTrace();
}
}
});
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