http post authentication failure 403 - android

I am trying to call a https post api from android app. It is giving 403 permission denied error. But the api works fine when called from postman or CURL in windows cmd.
In android i have tried Volley and OkHttpClient but the response from both is same.I am attaching codes for both libraries. Any help regarding this will be appreciated. Thanks in advance.
Volley
RequestQueue queue = Volley.newRequestQueue(getActivity());
String url = "https://xxxxx.com/api.php";
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Do something with the response.
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("content1", "xyz");
MyData.put("content2", "xyz");
return MyData;
}
}; queue.add(MyStringRequest);
OkHttpClient
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
.add("content1", "xyz")
.add("content1", "xyz")
.build();
okhttp3.Request request = new okhttp3.Request.Builder()
.url(url)
.post(formBody)
.build();
try {
okhttp3.Response response = client.newCall(request).execute();
// Do something with the response.
} catch (IOException e) {
e.printStackTrace();
}

make sure oyu have the correct content type in the header. for instance in Volley
#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;
}

Related

Send token in header using volley library in android

I'm trying to send Get request to server using volley library in android but it failed to get response but when I send the same request from Postman it success to get response. I must to send token parameter in header to get the response. what is the problem although I add token in the request in java code but it failed to get response ?
Android Java code
public static void sendPostRequest(Context context, String token, HashMap<String, String> parameters)
{
try {
StringRequest stringRequest = new StringRequest(Request.Method.GET, "http://api.palcharge.com/WS/listProviders?username=api",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
// handle response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toasty.warning(SelectBlog.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
public Map<String, String> getHeaders() {
HashMap<String, String> params = new HashMap<>();
params.put("token", token);
return params;
}
};
VolleySingleton.getInstance(context).addToRequestQueue(stringRequest);
Log.d("Request", stringRequest.getHeaders().toString());
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
Snapshot from Postman when I send request
#Override
public Map<String, String> getHeaders() {
HashMap<String, String> params = new HashMap<>();
params.put("Authorization", "Bearer " + token);
return params;
}

getHeaders Override method not being added to request

I'm trying to do a simple GET request in Android via Volley. However when I debug it the override method(s) are only called AFTER the request has been added to the queue. So my request thinks the headers object is empty and fails on the backend check. How can I make the request consume my headers before being sent to the backend?? I've looked at examples everywhere and I can't figure out why mine doesn't work. Please help!
private void getHello(){
String helloUrl = "https://...";
final String basicAuth = "Basic " + Base64.encodeToString("testUser:somePassword".getBytes(), Base64.NO_WRAP);
StringRequest stringRequest = new StringRequest(Request.Method.GET, helloUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("Hello Response: ",response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Hello Response Error: ",error.toString());
}
}){
#Override
public Map<String,String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
params.put("X-FXF-clientid", "123");
params.put("authorization", basicAuth);
return params;
}
};
queue.add(stringRequest);
}

Problem connecting spotify APIS using StringRequest

I'm trying to connect my android app to Spotify APIS.
Now I'm able to login, and play some random music with URL songs. My problem is I'm not able to connect using GET. And my only one response is:
E/Volley: [7721] BasicNetwork.performRequest: Unexpected response code 401 for
StringRequest stringRequest = new StringRequest(Request.Method.GET, URLline,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
parseData(response);
System.out.println("respuesta: " + response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("Accept", "application/json");
params.put("Content-Type", "application/json");
params.put("Authorization", "Bearer BQCljGDNl4xBRbSnJgl8O8tZU-OUIGGpBFsYZTD_QxcrHI-JN8-cFbfiewHTmSIlzMMuvRaX5lsPtDFwFsx_pNq37DEH8jll8sd9jXs6gPXGGTON0LOlzbzPXhAVz6mG_Ta-6BakiVo5C-MAjVL8UC9r9Hl8xIR_en9-tmpfCTKccEKI");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
I think the problem is that you are sending the headers as GET parameters, you should override getHeaders().
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("xxx", "xxx");
return params;
}

Sending form data in volley post request

The postman response is this image:
This is the code i am using to send the data in the post request. Although i am getting a 400 response code from this.
StringRequest stringRequest = new StringRequest(Request.Method.POST,
API.ADD_PAYMENT,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
onBackPressed();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(AddPaymentActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("amount", "123");
params.put("description", "Not Paid");
params.put("customer", "1");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json; charset=UTF-8");
headers.put("Authorization", "token 0ee1248c5a84e8b1e36a8a15da48c0bb7580926c");
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(AddPaymentActivity.this);
requestQueue.add(stringRequest);
First of all why don't you use JsonObjectRequest instead of StringRequest when you're using application/json as your talking language with server? Second have you tried passing your parameters to the other request constructor like below?
Map<String, Object> params = new HashMap<>();
params.put("amount", 123);
params.put("description", "Not Paid");
params.put("customer", 1);
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.POST, API.ADD_PAYMENT, new JSONObject(params), new Response.Listener<JSONObject>() {
...
Passing your headers are essential so the rest of you code remains as it is.

how to send post request with data in Volley?

This is my android code
JSONObject params = new JSONObject();
params.put("username","rajesh#gmail.com");
params.put("password","hellothere");
JsonObjectRequest loginRequest = new JsonObjectRequest(
Request.Method.POST,
"http://192.168.2.67/tmp/test.php",
params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.d("","");
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d("","");
}
});
requestQueue.add(loginRequest);
The server code in php
<?php
$usr = $_REQUEST['username'];
$pwd = $_REQUEST['password'];
$resp[$usr]=$pwd;
echo json_encode($resp);
?>
the response i'm getting is
{"":null}
I tried with apache http cleint and it worked prferectly
is there any way i can do this with volley?
To send parameters in request body you need to override either
getParams() or getBody() method of the request classes
Source: Asynchronous HTTP Requests in Android Using Volley
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("username", "SomeUser");
params.put("password", "blabla");
return params;
}
This is the way you should override getParams() method.

Categories

Resources