getHeaders Override method not being added to request - android

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

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

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

Getting 400 error while trying to get access token through url in android

I am working with oauth2 and using Volley networking library in android. I am trying to get access token by using below code. But I getting 400 Bad request as my response. What is wrong in my request ? I even tried putting content type as application/x-www-form-urlencoded but still no luck. What can be the main cause for error ?
StringRequest accessTokenRequest = new StringRequest(Request.Method.POST, oauthConfig.getTokenEndPointUrl(), new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Log.e("AccessTokenFromLogin", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put(OAuthConstants.GRANT_TYPE, "password");
params.put(OAuthConstants.USERNAME, userEmail);
params.put(OAuthConstants.PASSWORD, userPassword);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", "application/x-www-form-urlencoded");
if (isValid(clientId))
params.put(OAuthConstants.CLIENT_ID, clientId);
if (isValid(clientSecret))
params.put(OAuthConstants.CLIENT_SECRET, clientSecret);
if (isValid(scope))
params.put(OAuthConstants.SCOPE, scope);
Log.e("LoginActivity",clientId+" "+clientSecret+" "+scope);
return params;
}
};
Volley.newRequestQueue(this, hurlStack).add(accessTokenRequest);

Post Method using Volley not working

Hi i am using Volley for my login page. I need to pass data like this manner
{
userID : '-988682425884628921',
email :'aditya#vyas.com',
passwd : '123ss'
}
I am using POST Method to send data,I already check in DHC, The Api is working fine in DHC and I am getting JSON Response, But when i try with Volley i am not able to get response. and not even any error in my logcat.
JAVA code
RequestQueue mVolleyQueue = Volley.newRequestQueue(this);
CustomRequest req = new CustomRequest(Request.Method.POST,url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.v("tag","login response " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.v("tag","login error response " + error.getMessage());
}
}){
#Override
public Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("userID", "-988682425884628921");
params.put("email", "aditya#vyas.com");
params.put("passwd", "123ss");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
mVolleyQueue.add(req);
Error
05-28 09:20:14.696 2450-2468/com.android.msahakyan.expandablenavigationdrawer E/tag﹕ parseNetworkError is ! null
05-28 09:20:14.697 2450-2468/com.android.msahakyan.expandablenavigationdrawer E/tag﹕ parseNetworkError status code : 400
05-28 09:20:14.697 2450-2468/com.android.msahakyan.expandablenavigationdrawer E/tag﹕ parseNetworkError message : <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request - Invalid Header</h2>
<hr><p>HTTP Error 400. The request has an invalid header name.</p>
</BODY></HTML>
}
Solved your problem. Just used JsonArrayRequest and passed parameters in JsonObject form:
Map<String, String> params = new HashMap<String, String>();
params.put("userID", "userid");
params.put("email","email");
params.put("passwd", "password");
JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST, "url", new JSONObject(params),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
System.out.println("response -->> " + response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("change Pass response -->> " + error.toString());
}
});
request.setRetryPolicy(new
DefaultRetryPolicy(60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(activity).add(request);
No need of overriding getParams() or getHeaders().
Problem : 1
You were getting response code 500 because the server was accepting the params as JsonObject and we are trying to feed String.
Problem : 2
You were using JsonObjectRequet but the response from the server was in JsonArray so you need to use JsonArrayRequest to accept the response in JsonArray
Try and let me know this helps or not :)
I had a similar problem. I had overwritten the Content-Type in the getHeaders Method:
headers.put("Content-Type", "application/json; charset=UTF-8");
but Volley itself added a Content-Type parameter, so there were two of those parameters. Delete the line had solved my Problem.
You need to override protected Map<String, String> getParams() to pass parameters in POST.
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Login Response", response.toString());
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.getStackTrace());
VolleyLog.d("ErrorVolley", "Error: " + error.getStackTrace());
hidepDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("userID", "2"));
params.put("email","aa#a.kl");
params.put("passwd", "ddddd");
return params;
}
};
Beware of content-type header. Volley handles it differently from other headers and it's not shown in Map<> Headers. Instead of overriding getHeaders() method to set content-type, you should override getBodyContentType() like this:
#Override
public String getBodyContentType()
{
return "application/json; charset=utf-8";
}
i have same problem use this :
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(LoginActivity.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
public Map<String, String> getParams() {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
headers.put("UN", UserName);
headers.put("PW", PassWord);
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
Just need to add headers.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); to parms
good luck.

Android Volley POST string in body

I'm trying to use Volley library to communicate with my RESTful API.
I have to POST string in the body, when I'm asking for the bearer Token. String should look like this:
grant_type=password&username=Alice&password=password123
And header:
Content-Type: application/x-www-form-urlencoded
More info about WebApi Individual Accounts:
http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api
Unfortunately I can't figure out how can I solve it..
I'm trying something like this:
StringRequest req = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.v("Response:%n %s", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", "User0");
params.put("password", "Password0");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
return headers;
}
};
I'm getting 400 Bad Request all the time.
I think that I'm actually sending request like this:
grant_type:password, username:User0, password:Password0
instead of:
grant_type=password&username=Alice&password=password123
I would be very grateful if anyone has any ideas or an advice..
To send a normal POST request (no JSON) with parameters like username and password, you'd usually override getParams() and pass a Map of parameters:
public void HttpPOSTRequestWithParameters() {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://www.somewebsite.com/login.asp";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR","error => "+error.toString());
}
}
) {
// this is the relevant method
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
// volley will escape this for you
params.put("randomFieldFilledWithAwkwardCharacters", "{{%stuffToBe Escaped/");
params.put("username", "Alice");
params.put("password", "password123");
return params;
}
};
queue.add(postRequest);
}
And to send an arbitary string as POST body data in a Volley StringRequest, you override getBody()
public void HttpPOSTRequestWithArbitaryStringBody() {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://www.somewebsite.com/login.asp";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR","error => "+error.toString());
}
}
) {
// this is the relevant method
#Override
public byte[] getBody() throws AuthFailureError {
String httpPostBody="grant_type=password&username=Alice&password=password123";
// usually you'd have a field with some values you'd want to escape, you need to do it yourself if overriding getBody. here's how you do it
try {
httpPostBody=httpPostBody+"&randomFieldFilledWithAwkwardCharacters="+URLEncoder.encode("{{%stuffToBe Escaped/","UTF-8");
} catch (UnsupportedEncodingException exception) {
Log.e("ERROR", "exception", exception);
// return null and don't pass any POST string if you encounter encoding error
return null;
}
return httpPostBody.getBytes();
}
};
queue.add(postRequest);
}
As an aside, Volley documentation is non-existent and quality of StackOverflow answers is pretty bad. Can't believe an answer with an example like this wasn't here already.
First thing, I advise you to see exactly what you're sending by either printing to the log or using a network sniffer like wireshark or fiddler.
How about trying to put the params in the body? If you still want a StringRequest you'll need to extend it and override the getBody() method (similarly to JsonObjectRequest)
I know this is old, but I ran into this same problem and there is a much cleaner solution imo found here: How to send a POST request using volley with string body?

Categories

Resources