Unexpected response code 500 for POST method Volley error - java

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

Related

Is it possible to get a response as a json file instead of making him a jsonobject in java?

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);
}

How do I read header from Volley request's JSON response?

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.

Volley Authorization Required

I am trying to convert Unirest
HttpResponse<String> response = Unirest.post("https://api.tap.company/v2/charges")
.header("authorization", "Bearer sk_test_XKokBfNWv6FIYuTMg5sLPjhJ")
.header("content-type", "application/json")
.body("{\"amount\":1,\"currency\":\"KWD\",\"receipt\":{\"email\":false,\"sms\":true},\"customer\":{\"first_name\":\"test\",\"phone\":{\"country_code\":\"965\",\"number\":\"50000000\"}},\"source\":{\"id\":\"src_kw.knet\"},\"redirect\":{\"url\":\"http://your_website.com/redirect_url\"}}")
.asString();
to Volley
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://api.tap.company/v2/charges";
StringRequest TapREQUEST = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override public void onResponse(String response) {
Log.w("OnResponse:", response);
}
}, new Response.ErrorListener() {
#Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); }
}) {
#Override public Map<String, String> getHeaders() {
Map<String,String> headers = new HashMap<>();
headers.put("content-type", "application/json");
headers.put("authorization", "Bearer sk_test_XKokBfNWv6FIYuTMg5sLPjhJ");
//String auth = "Bearer " + Base64.encodeToString("sk_test_XKokBfNWv6FIYuTMg5sLPjhJ".getBytes(), Base64.DEFAULT);
//headers.put("authorization", auth);
return headers;
}
#Override protected Map<String,String> getParams() {
Map<String,String> params = new HashMap<>();
params.put("amount", String.valueOf(9.500));
params.put("currency","KWD");
params.put("receipt","{'email':false,'sms':true}");
params.put("customer",":{'first_name':'test','phone':{'country_code':'965','number':'50000000'}}");
params.put("source","{'id':'src_kw.knet'}");
params.put("redirect",":{'url':'http://ib7ar.com'}");
return params;
}
};
queue.add(TapREQUEST);
but I get
E/Volley: [396] BasicNetwork.performRequest: Unexpected response code 400 for https://api.tap.company/v2/charges
When I click on link I get
{"errors":[{"code":"2107","description":"Authorization Required"}]}
You have to set body parameters in different way. Let's create method returning correct string:
#NotNull
private JSONObject getJsonObject() {
JSONObject params = new JSONObject();
try {
params.put("amount", "1");
params.put("currency", "KWD");
JSONObject receipt = new JSONObject();
receipt.put("email", "false");
receipt.put("sms", "true");
params.put("receipt", receipt);
JSONObject customer = new JSONObject();
customer.put("first_name", "test");
JSONObject phone = new JSONObject();
phone.put("country_code", "965");
phone.put("number", "50000000");
customer.put("phone", phone);
params.put("customer", customer);
JSONObject id = new JSONObject();
id.put("id", "src_kw.knet");
params.put("source", id);
JSONObject url = new JSONObject();
url.put("url", "http://ib7ar.com");
params.put("redirect", url);
} catch (JSONException e) {
e.printStackTrace();
}
return params;
}
And now instead of getParams() you need getBody() method:
#Override
public byte[] getBody() {
try {
return getJsonObject().toString().getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}

WP Rest API OAuth1 Authentication in Android using volley library

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.

Parsing JSONArray using Gson + Volley not getting response

So I am trying to parse an array of objects from json using Google's Gson library and Volley for HTTP requests. My issue is it's as if the code isn't 'hitting' the OnResponse call. I've tried adding a simple Log printout within the function just to see if it does anything.
My GsonRequest class comes straight from Google's Training Docs. I constructed these methods based on an answer to this question.
This is my code:
private void runVolleyJson() throws AuthFailureError {
GsonRequest<Meetings> getMeetings = new GsonRequest<Meetings>(AUTH_URL, Meetings.class, getHeaders(),
createMyReqSuccessListener(),
createMyReqErrorListener());
helper.add(getMeetings);
}
private Response.Listener<Meetings> createMyReqSuccessListener() {
return new Response.Listener<Meetings>() {
#Override
public void onResponse(Meetings response) {
// NOTHING HAPPENS FROM HERE!
try {
Log.d("response", response.toString());
} catch (Exception e) {
e.printStackTrace();
}
// Do whatever you want to do with response;
// Like response.tags.getListing_count(); etc. etc.
}
};
}
private Response.ErrorListener createMyReqErrorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Do whatever you want to do with error.getMessage();
}
};
}
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> map = new HashMap<>();
map.put("Content-Type", "application/json;");
map.put("Authorization", "Bearer <sometoken>");
return map;
}
There is absolutely no error. It is authorizing the request, but nothing happens in OnResponse, it just seems to ignore that function.
Now I've tried using a standard StringRequest with volley and it works flawlessly, like this:
private void runVolleyTest() {
StringRequest request = new StringRequest(Request.Method.GET, AUTH_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonarray = new JSONArray(response);
for(int i = 0; i < jsonarray.length(); i++) {
Gson gson = new Gson();
Meeting m = gson.fromJson(jsonarray.get(i).toString(), Meeting.class);
Log.e("Meeting", m.getMeetingId() + " " + m.getStatus());
}
} catch (JSONException e) {
e.printStackTrace();
}
;
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
txtError(error);
}
}) {
#Override
public Map<String, String> getHeaders() {
HashMap<String, String> map = new HashMap<>();
map.put("Content-Type", "application/json;");
map.put("Authorization", "Bearer <sometoken>");
return map;
}
};
//request.setPriority(Request.Priority.HIGH);
helper.add(request);
}
Try adding this line at the beginning
RequestQueue helper = Volley.newRequestQueue(mContext);
Add these line
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
if you don't want to the save response in cache memory then add this
requestQueue.add(stringRequest);
According to my personal opinion its better if you pass the application context.

Categories