I'm trying to send GET request to Wordpress rest api from my Android app.
In postman I send POST and GET request which worked but when I send a request with the same headers I get com.android.volley.AuthFailureError .
Here's my code
public void getSlides(final onSlideReceived onSlideReceived) {
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET,
BASE_URL + "slider", null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Toast.makeText(context, response.toString(), Toast.LENGTH_LONG).show();
Log.i(ITAGSLIDE, "onResponse: "+response);
onSlideReceived.onReceived(slides);
}
} , new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, error.toString(), Toast.LENGTH_SHORT).show();
Log.e(ETAGSLIDE, "onErrorResponse: "+error.toString() );
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<>();
Map<String,String> params = new HashMap<>();
params.put("oauth_consumer_key",CONSUMER_KEY);
params.put("oauth_nonce", OAUTH_NONCE);
params.put("oauth_signature_method",OAUTH_SIGNATURE_METHOD);
params.put("oauth_timestamp",OAUTH_TIMESTAMP);
params.put("oauth_token", OAUTH_TOKEN);
params.put("oauth_version",OAUTH_VERSION);
String encodedParams = mapToStringAnd(params);
String string_to_sign = "";
try {
string_to_sign = (new StringBuilder("GET&"))
.append(URLEncoder.encode(
BASE_URL+"slider", "utf-8")).append("&")
.append(URLEncoder.encode(encodedParams, "utf-8")).toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.d("string to sign", string_to_sign);
try {
Mac mac = Mac.getInstance("HMAC-SHA1");
String secret = CONSUMER_SECRET + "&" + OAUTH_TOKEN_SECRET;
Log.d("secret", secret);
mac.init(new SecretKeySpec(secret.getBytes("utf-8"), "HMAC-SHA1"));
OAUTH_SIGNATURE = Base64.encodeToString(mac.doFinal(string_to_sign.getBytes("utf-8")), 0).trim();
Log.d("signature", OAUTH_SIGNATURE);
} catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
e.printStackTrace();
}
String query =
"oauth_consumer_key=\""+CONSUMER_KEY+"\""+
",oauth_token=\""+OAUTH_TOKEN+"\""+
",oauth_signature_method=\""+OAUTH_SIGNATURE_METHOD+"\""+
",oauth_timestamp=\""+OAUTH_TIMESTAMP+"\""+
",oauth_nonce=\""+OAUTH_NONCE+"\""+
",oauth_version=\""+OAUTH_VERSION+"\""+
",oauth_signature=\""+OAUTH_SIGNATURE+"\"";
Log.d("query","OAuth "+query);
headers.put("Authorization","OAuth "+query);
return headers;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(18000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(context).add(request);
}
Finally here's my header query which I get in logcat:
OAuth oauth_consumer_key="*****",oauth_token="******",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1545421361",oauth_nonce="8.308277993153459E7",oauth_version="1.0",oauth_signature="*******"
Where is my mistake? How should I send request to get a response?
Thanks a lot for any help.
Related
So i have a get request from an API, when i get the response i want to make that response into a json file instead of making him an JSONOBJECT, is it possible ? i will paste the get funcion here, and the way im getting the JSONOBJECT.
I want to replace the way i get a JSONOBJECT, from a way to get that json as a file that goes to my assets directory.
public void getAssetPlant(final VolleyCallBack callBack) {
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.GET, url_assets, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject j = new JSONObject(response);
callBack.onSuccess();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MapActivity.this, "Failed to gather info" + error.networkResponse.statusCode, Toast.LENGTH_SHORT).show();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer " + token);
return headers;
}
};
requestQueue.add(request);
}
I'm using volley for my post requests and the issue is when I send 362 requests on queue to the server the data will save even though there's an error response as I assumed, or there are repeating data stored in the database.Sometimes my network connectivity is slow. Let's say I send 362 data to my server and I have 3 error response, when the sync was done the overall total of the saved data is still 362 and it should 359 since I have 3 error response, currently I have condition when the error response received the data should not save to the server.
This is what I've tried
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject data = new JSONObject(response);
String status = data.getString("status");
String description = data.getString("description");
JSONObject dataObject = data.getJSONObject("data");
String household = dataObject.getString("hh_id");
if (status.matches("success")){
progressCC[0]++;
progressPercent = findViewById(R.id.progressCount);
progressBar = findViewById(R.id.progressBar);
progressCount = findViewById(R.id.progressFigure);
Double progressCalc = progressCC[0] / countEmvDetails * 100;
progressCount.setText(String.valueOf(progressCC[0].intValue()));
progressPercent.setText(String.valueOf(progressCalc.intValue()));
progressBar.setProgress(progressCalc.intValue());
lst.add(description + "household id: " + household);
gvMain.setAdapter(adapter);
if (progressPercent.getText().toString().matches("100")) {
Toasty.success(SyncData.this, "Completed", Toast.LENGTH_SHORT, true).show();
Toasty.success(SyncData.this, "Updating local data please wait!", Toast.LENGTH_SHORT, true).show();
updaterEmvMonitoring();
}
sqLiteHelper.storeLogs("sync", hh_id);
sqLiteHelper.deleteEmvMonitoringDetails(id);
}
else{
btnSync.setEnabled(true);
lst2.add("Error on syncing the data!");
gvMain2.setAdapter(adapter2);
Toasty.error(getApplicationContext(), "Error on pulling data.", Toast.LENGTH_SHORT, true).show();
}
} catch (JSONException e) {
btnSync.setEnabled(true);
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// method to handle errors.
btnSync.setEnabled(true);
sqLiteHelper.storeLogs("error", hh_id);
try {
String responseBody = new String(error.networkResponse.data, "utf-8");
Integer responseCode = error.networkResponse.statusCode;
if (responseCode == 401) {
JSONObject data = new JSONObject(responseBody);
JSONArray errors = data.getJSONArray("errors");
JSONObject jsonMessage = errors.getJSONObject(0);
String message = jsonMessage.getString("message");
Toasty.warning(SyncData.this, message, Toast.LENGTH_SHORT, true).show();
lst2.add(message);
gvMain2.setAdapter(adapter2);
} else if (responseCode == 404) {
JSONObject data = new JSONObject(responseBody);
String desc = data.getString("description");
Toasty.error(SyncData.this, "Error 404:" + desc, Toast.LENGTH_SHORT, true).show();
lst2.add(desc);
gvMain2.setAdapter(adapter2);
}
} catch (Exception e) {
Log.d("Error co", String.valueOf(e));
lst2.add(String.valueOf(e));
gvMain2.setAdapter(adapter2);
Toasty.error(SyncData.this, "Network not found.", Toast.LENGTH_SHORT, true).show();
}
}
}) {
#Override
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer " + token);
return headers;
}
protected Map<String,String> getParams(){
Map<String, String> params = new HashMap<>();
params.put("full_name", full_name);
return params;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 5,
0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
I'm finding the following error with my request post method: Unexpected response code 500 for POST method.
It was working fine and then it just stopped working and started to display this error.
this is my post method:
private void postRequest(String empresa, String matricula, String foto, String data, String face) {
RequestQueue requestQueue=Volley.newRequestQueue(MainActivity.this);
String url="http://can't show the url";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//anĂ¡lise de dados json
try {
JSONObject jsonObject = new JSONObject(response);
}
catch (Exception e){
e.printStackTrace();
// post_response_text.setText("POST DATA : unable to Parse Json");
}
Log.d("Response", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// post_response_text.setText("Post Data : Response Failed");
Log.d("Error.Response", error.toString());
}
})
{
#Override
protected Map<String,String> getParams(){
Map<String,String> params=new HashMap<String, String>();
params.put("Id", "");
params.put("Empresa", empresa);
params.put("Matricula", matricula);
params.put("Foto", foto);
params.put("Data", data);
params.put("GPS", finalLatitude + "|" + finalLongitude);
params.put("idDispositivo", getIMEI());
params.put("arquivo", "");
params.put("face", face);
params.put("ip", getIP());
return params;
}
#Override
public Map<String,String> getHeaders() throws AuthFailureError {
Map<String,String> params=new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(stringRequest);
}
I tried to do the post request on postman and it's working fine.
How i'm sending information on postman: postman image
I am developing an application where Logging In returns a cookie named "authCookie" from server and this cookie is in header of the response. I am using Volley library and String Request for server-mobile application communication. Can you please guide me how do I get this cookie from header?
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
if(obj.has("csrf") && obj.has("refreshToken")){
csrf = obj.getString("csrf");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null){
if(error.networkResponse.statusCode == 400){
Toast.makeText(MainActivity.this,"Invalid username/password",Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(MainActivity.this,"Check internet connection!",Toast.LENGTH_LONG).show();
}
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
I want authCookie from response and save it in a string.
I am new to using Volley on Android. Using the old http client stuff I could make my web requests perfectly with the various headers and parameters, now I am unable. My request looks like this in Postman:
POST /token HTTP/1.1
Host: my.api.co.za
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
username=test&password=1234&grant_type=password
Yet I am unable to recreate and execute this request in Volley. I have tried making a custom Json request class that extends Request<JSONObject> but to no avail. Please see my code below:
public class CustomJsonRequest extends Request<JSONObject> {
private Response.Listener<JSONObject> listener;
private Map<String, String> params;
public CustomJsonRequest(int method, String url, Listener<JSONObject> responseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = responseListener;
}
#Override
public Map getHeaders() throws AuthFailureError {
Map headers = new HashMap();
headers.put("Accept", "application/json");
headers.put("Content-Type", "application/x-www-form-urlencoded");
return headers;
}
#Override
public byte[] getBody() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", "test");
params.put("password", "1234");
params.put("grant_type", "password");
if (params != null && params.size() > 0) {
return encodeParameters(params, getParamsEncoding());
}
return null;
}
/**
* Converts <code>params</code> into an application/x-www-form-urlencoded encoded string.
*/
private byte[] encodeParameters(Map<String, String> params, String paramsEncoding) {
StringBuilder encodedParams = new StringBuilder();
try {
for (Map.Entry<String, String> entry : params.entrySet()) {
encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
encodedParams.append('=');
encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
encodedParams.append('&');
}
encodedParams.deleteCharAt(encodedParams.lastIndexOf("&"));
Log.e("params", encodedParams.toString());
return encodedParams.toString().getBytes(paramsEncoding);
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
}
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
Log.e("response", response.toString());
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
Log.e("response", response.toString());
listener.onResponse(response);
}
private Priority mPriority;
public void setPriority(Priority priority) {
mPriority = priority;
}
#Override
public Priority getPriority() {
return mPriority == null ? Priority.NORMAL : mPriority;
}
}
And I call this as follows in my MainActivity class:
CustomJsonRequest request = new CustomJsonRequest(Request.Method.POST, AUTH_URL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//showJSON(response);
VolleyLog.v("Response:%n %s", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
txtError(error);
}
});
Can somebody tell me where I am going wrong in creating this request?
You can try with my following sample code:
String url = "http://server/token";
Map<String, String> stringMap = new HashMap<>();
stringMap.put("grant_type", "password");
stringMap.put("username", "bnk");
stringMap.put("password", "bnk123");
Uri.Builder builder = new Uri.Builder();
Iterator entries = stringMap.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString());
entries.remove();
}
String requestBody = builder.build().getEncodedQuery();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, requestBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// do something...
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something...
}
}){
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
};
UPDATE:
If your project uses Google's official volley as a module, you should add the following into JsonObjectRequest.java file:
public JsonObjectRequest(int method, String url, String requestBody,
Listener<JSONObject> listener, ErrorListener errorListener) {
super(method, url, requestBody, listener, errorListener);
}
UPDATE 2:
If you don't want to edit JsonObjectRequest.java file as I mentioned above, you can use the following code:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// do something...
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something...
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
#Override
public byte[] getBody() {
// init parameters
Map<String, String> params = new HashMap<>();
params.put("grant_type", "password");
params.put("username", "bnk");
params.put("password", "bnk123");
// encode parameters (can use Uri.Builder as above)
String paramsEncoding = "UTF-8";
StringBuilder encodedParams = new StringBuilder();
try {
for (Map.Entry<String, String> entry : params.entrySet()) {
encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
encodedParams.append('=');
encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
encodedParams.append('&');
}
return encodedParams.toString().getBytes(paramsEncoding);
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
}
}
};
Hope it helps!