I want to send a DELETE request to an API to delete a city with the given id. In the API request documentation it says that the DELETE request requires as parameters the authentication token and the city id. When I run the code below I always get a com.android.volley.AuthFailureError.
Here's my code:
void deleteCity(String cityId, final VolleyResponseListener volleyResponseListener){
String url = baseUrl + "city";
try {
JSONObject params = new JSONObject();
params.put("token", token);
params.put("city_id", cityId);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.DELETE, url, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
String success = response.get("success").toString();
if(success.equals("true")){
volleyResponseListener.onResponse();
}else{
String errorMessage = response.get("errorMessage").toString();
throw new Exception(errorMessage);
}
} catch (Exception e) {
volleyResponseListener.onError(e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
volleyResponseListener.onError("Volley Error");
}
});
requestQueue.add(jsonObjectRequest);
}catch (JSONException e){
volleyResponseListener.onError("Param error");
}
}
UPDATE:
I solved the problem by adding the city id as a query in the HTTP request and sent the authentication token in the header. Here is the final code:
void deleteCity(String cityId, final VolleyResponseListener volleyResponseListener){
String url = baseUrl + "city?city_id="+cityId;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.DELETE, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
String success = response.get("success").toString();
if(success.equals("true")){
volleyResponseListener.onResponse();
}else{
String errorMessage = response.get("errorMessage").toString();
throw new Exception(errorMessage);
}
} catch (Exception e) {
volleyResponseListener.onError(e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
volleyResponseListener.onError("Volley Error");
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
headers.put("token", token);
return headers;
}
};
requestQueue.add(jsonObjectRequest);
}
Related
I want to update the "Pass" field using WebAPI, I have created an HTTP PUT Request using Asp.Net WEB API and Android Java with Volley.
through Postman it's updating field value but when I test through my App it's updating the blank value in DB.
Thanks in advance.
private void callPUTDataMethod(String name, String job) {
loadingPB.setVisibility(View.VISIBLE);
String url = URL;
RequestQueue queue = Volley.newRequestQueue(PassUpdt.this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.PUT, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
loadingPB.setVisibility(View.GONE);
jobEdt.setText("");
userNameEdt.setText("");
// on below line we are displaying a toast message as data updated.
Toast.makeText(PassUpdt.this, "Data Updated..", Toast.LENGTH_SHORT).show();
try {
JSONObject jsonObject = new JSONObject("Pass");
String output = "Password Updated";
responseTV.setText(output);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(PassUpdt.this, "Fail to update data..", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("EmpCd", "P010");
params.put("Pass", "12345");
params.put("Content-Type", "application/json; charset=utf-8");
return params;
}
};
queue.add(jsonObjectRequest);
}
}
I sent request with postman its working, but volley doesn't work. I always get error! I searched stackoverflow volley returns error when response is empty but i added CustomJsonObjectRequest still the issue remains.
Error message
Volley org.json.JSONException: End of input at character 0 of
CustomJsonObjectRequest
public class CustomJsonObjectRequest extends JsonObjectRequest {
public CustomJsonObjectRequest(int method, String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
if (response.data.length == 0) {
byte[] responseData = "{}".getBytes("UTF8");
response = new NetworkResponse(response.statusCode, responseData, response.headers, response.notModified);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return super.parseNetworkResponse(response);
}
}
Volley request
EcoElement ecoElement = ecoElementArrayList.get(position);
Map<String, String> params = new HashMap<String, String>();
params.put("Id", ecoElement.getId().toString());
params.put("Checked", ecoElement.getChecked().toString());
JSONObject ObjParams = new JSONObject(params);
try {
CustomJsonObjectRequest getRequest = new CustomJsonObjectRequest(Request.Method.PUT, "https://ourwebsite.sslbeta.de/api/gardenapi/updateecoelements", ObjParams,
response -> {
Toast.makeText(getContext(), ""+response, Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
},
error -> {
Toast.makeText(getContext(), ""+error.toString(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
);
RequestQueueSingleton.getInstance(getContext()).addToRequestQueue(getRequest);
} catch (Exception e) {
Toast.makeText(getContext(), e.toString(), Toast.LENGTH_LONG).show();
}
Finally i was able to fix the issues after hours of searching. There were two reasons to this, first is that api was returning null/empty so CustomJsonObjectRequest fixed that, and then another issue is that i forgot to add authentication headers. that was a silly mistake i know!
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "Bearer "+access_token);
return headers;
}
};
Here is the solution, just create this method and pass your value.
private void CustomJsonObjectRequest() {
String tag_string_req = "req__details";
StringRequest strReq = new StringRequest(Request.Method.POST, <API URL>, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
getPerspective().showErrorLogs(TAG, "Response Invest : " + response);
try {
// Parse your response here
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("Id", <ID VALUE HERE>);
params.put("Checked", <TRUE or FALSE>);
return params;
}
};
strReq.setRetryPolicy(new RetryPolicy() {
#Override
public void retry(VolleyError arg0) throws VolleyError {
}
#Override
public int getCurrentTimeout() {
return 0;
}
#Override
public int getCurrentRetryCount() {
return 0;
}
});
strReq.setShouldCache(false);
addToRequestQueue(strReq, tag_string_req);
}
Both ID and Checked must have String type.And create below methods in MainActivity:
private RequestQueue mRequestQueue;
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
I am trying to retrieve data from server using volley, but when I call this method the first time, I get the response from server, but null is returned by the method. If I call it the second time I get the last response.
public String retrieveDataFromServer(String url, String param, final String token){
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
data = new JSONObject(response).toString();
}catch (Exception e){}
//Toast.makeText(getApplicationContext(), "wow" + data, Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
try{
data = new JSONObject(error.toString()).toString();
}catch (Exception e){}
//Toast.makeText(getApplicationContext(), "" +data, Toast.LENGTH_SHORT).show();
}
}) {
/**
* Passing some request headers
*/
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
String bearer = "Bearer ".concat(token);
Map<String, String> headersSys = super.getHeaders();
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
//headers.put("token", token);
headersSys.remove("Authorization");
headers.put("Authorization", bearer);
headers.putAll(headersSys);
return headers;
}
};
// Adding request to request queue
addToRequestQueue(stringRequest);
//Toast.makeText(getApplicationContext(), "wow" + data, Toast.LENGTH_SHORT).show();
return data;
}
How do I get the response on first call of method?
You can use call back to return Volley response:
public void retrieveDataFromServer(final VolleyCallback callback) {
StringRequest strReq = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
callback.onSuccess(response);
}
}
}}
Create interface:
public interface VolleyCallback{
void onSuccess(String response);
}
And get result from activity:
String yourString = "";
#override
public void onResume() {
super.onResume();
retrieveDataFromServer(new VolleyCallback(){
#Override
public void onSuccess(String response){
//Get result from here
yourString = response;
}
});
}
I am getting a timeout error on my request in my android app. I have set the retry policy but it did not solve the issue. When tested on my emulator it works fine with no error, but when using a real device to test it gives the timeout error.
public void makeRequest(final String user, final String cred)
{
String url = "http://10.0.2.2:8888/map/api/login";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
try
{
JSONObject jsonResponse = new JSONObject(response);
String status = jsonResponse.getString("status");
String token = jsonResponse.getString("token");
if(status.equalsIgnoreCase("error"))
{
Snackbar.make(findViewById(R.id.myCoordinatorLayout), jsonResponse.getString("message"), Snackbar.LENGTH_LONG).show();
}
else if (status.equalsIgnoreCase("success"))
{
System.out.println(jsonResponse);
Intent loader = new Intent(home.this,webViewActivity.class);
loader.putExtra(EXTRA_MESSAGE,token);
startActivity(loader);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
error.printStackTrace();
}
}
){
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
params.put("portal[username]", user);
params.put("portal[password]", cred);
params.put("portal[From]","web");
return params;
}
};
postRequest.setRetryPolicy(new DefaultRetryPolicy(
7000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(getApplicationContext()).add(postRequest);
}
The error i get is below
08-18 12:42:46.341 16112-16112/com.mobile.map.map_mobile W/System.err: com.android.volley.TimeoutError
08-18 12:42:46.341 16112-16112/com.mobile.map.map_mobile W/System.err: at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:141)
08-18 12:42:46.341 16112-16112/com.mobile.map.map_mobile W/System.err: at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112)
Can you check on the different device and on the different network. If it doesn't work please check the response time in postman if it is more than 2500 millisecond(volley default timeout), increase the volley's default timeout in DefaultRetryPolicy.class
I am assuming that your Key value pair is for Body.
JSONObject params = new JSONObject();
try {
params.put("portal[username]", user);
params.put("portal[password]", cred);
params.put("portal[From]","web");
} catch (JSONException e) {
// Do something
}
Response.Listener<JSONObject> jsonObjectListener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Response here
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Error here
}
};
String url = "http://10.0.2.2:8888/map/api/login";
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, params,
jsonObjectListener, errorListener);
Volley.newRequestQueue(getApplicationContext()).add(jsonRequest);
I feel like this is a very basic concept missunderstanding. In my Android app I make HTTP requests using Volley lib. At first I made the requests through a JsonObjectRequest in the Activity code and worked right, but now I separated the request code in a class apart so I can call it from any Activity. The new class has a method that returns the requested JSONObject but any "json action" I do over the returned object ends in an error.
Here is the new class code, JSONRequests:
public class JSONRequests {
private JSONObject mResponse;
private String mURL = "https://myurl.com/";
public JSONObject getJSONObject(final String credentials, final String path) {
final JsonObjectRequest mRequest = new JsonObjectRequest(mURL.concat(path), null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
mResponse = response;
try {
Log.d("RESPONSE", mResponse.getString("id")); // It works here
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "Basic " + credentials);
return headers;
}
};
MyApplication.getInstance().getRequestQueue().add(mRequest);
return mResponse;
}
}
And here is how I call getJSONObject from MyActivity:
JSONRequests mRequest = new JSONRequests();
JSONObject mInfo = mRequest.getJSONObject(mEncodedCredentials, mPath);
try {
Log.d("RESPONSE", mInfo.getString("id")); // This doesn't work
} catch (JSONException e) {
e.printStackTrace();
}
When in the Activity file, I used "response" as a JSONObject and it worked, but now separated it won't. I don't know if is a error with JSONObject or just that I'm not getting the returned object in the correct way. Thanks in advance.