Android Volley POST string in body - android

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?

Related

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

Adding parameters on Restful API using JsonObjectRequest on Android Studio

I'm calling a restful api on my android project and I used Volley and JsonObjectRequest, I thought that the third parameter of the JsonObjectRequest which is jsonRequest are the api parameters so I created a json object for that which in the end I only got errors. So is it common to directly add the api parameters on the url? instead of passing it on a json object? what is the third parameter for, it would be really helpful if someone can give me an example. And my last question is how do you get the entire json response instead of using response.getString("title") for each key.
//api parameters directly added on the url
String URL = "https://www.myapi.com/?param=sample&param1=sample1";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String title = response.getString("Title");
Log.d("title", title);
} catch(Exception e){
Log.e("response error", e.toString());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, error.toString());
}
});
Below your Response.ErrorListener() you need to add these two overrides:
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, error.toString());
}) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("param", "sample");
params.put("param1", "sample1);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/x-www-form-urlencoded; charset=UTF-8");
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
return headers;
}
};

Pass Parameter with Volley POST

I was able to call an HTTP endpoint using Postman and these parameters:
{
"name":"Val",
"subject":"Test"
}
However I am unable to do the same with Volley through Android: Here is trying to use JSONRequest:
HashMap<String, String> params2 = new HashMap<String, String>();
params.put("name", "Val");
params.put("subject", "Test Subject");
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.POST, Constants.CLOUD_URL, new JSONObject(params2), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
mView.showMessage("Response: " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
mView.showMessage(error.getMessage());
}
});
// Access the RequestQueue through your singleton class.
VolleySingleton.getInstance(mContext).addToRequestQueue(jsObjRequest);
And here is trying StringRequest
private void postMessage(Context context, final String name, final String subject ){
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.POST, Constants.CLOUD_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mView.showMessage(response);
}
}, 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("name", name);
params.put("subject", subject);
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;
}
};
queue.add(sr);
}
When I use JSONRequest, the call POSTs but no parameter is passed and when I use StringRequest I get the error below? How can I pass JSON data to Volley call?
E/Volley: [13053] BasicNetwork.performRequest: Unexpected response code 400 for
Here is the server code that handles the request
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
var helloRequest = await req.Content.ReadAsAsync<HelloRequest>();
var name = helloRequest?.Name ?? "world";
var responseMessage = $"Hello {personToGreet}!";
log.Info($"Message: {responseMessage}");
return req.CreateResponse(HttpStatusCode.OK, $"All went well.");
}
public class HelloRequest
{
public string Name { get; set; }
public string Subject { get; set; }
}
The server code is expecting a JSON object is returning string or rather Json string.
JsonObjectRequest
JSONRequest sends a JSON object in the request body and expects a JSON object in the response. Since the server returns a string it ends up throwing ParseError
StringRequest
StringRequest sends a request with body type x-www-form-urlencoded but since the server is expecting a JSON object. You end up getting 400 Bad Request
The Solution
The Solution is to change the content-type in the string request to JSON and also pass a JSON object in the body. Since it already expects a string you response you are good there. Code for that should be as follows.
StringRequest sr = new StringRequest(Request.Method.POST, Constants.CLOUD_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mView.showMessage(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mView.showMessage(error.getMessage());
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
HashMap<String, String> params2 = new HashMap<String, String>();
params2.put("name", "Val");
params2.put("subject", "Test Subject");
return new JSONObject(params2).toString().getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
Also there is a bug here in the server code
var responseMessage = $"Hello {personToGreet}!";
Should be
var responseMessage = $"Hello {name}!";
Add the content type in the header
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
You are using params.put instead of params2.put in your hash map while passing parameters.
because your object name is params2

String Request Unexpected response Code 415

When I'm using Postman,
Putting values from raw works perfectly.
But in Android, I am receiving Error Code 415.
REVIEW_URL = "http://somesite.esy.es/api.php/registration";
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest request = new StringRequest(Request.Method.POST, REVIEW_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("RESPONSE:", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ERROR",""+error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String,String>();
params.put("device_id", "11111");
return params;
}
#Override
public String getBodyContentType() {
return "application/raw";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String,String>();
params.put("Content-Type", "application/raw");
return params;
}
};
requestQueue.add(request);
Am I doing it right chaging content type to raw? thanks.
your content type is not supported, so I suggest changing it to
"application/json"
this worked for me.
as shown here, this is the correct one.
thanks, hope it helps.
JsonObjectRequest use this Volly Object is right.

StringRequest with JSON body

I'm trying to send a request using Volley but I can't figure how to make it work.
I need to send a POST request with JSON encoded data as the body, but after hours of trying different things I still can't make it work.
This is my current code for the request:
User user = User.getUser(context);
String account = user.getUserAccount();
String degreeCode = user.getDegreeCode();
final JSONObject body = new JSONObject();
try {
body.put(NEWS_KEY, 0);
body.put(NEWS_DEGREE, degreeCode);
body.put(NEWS_COORDINATION, 0);
body.put(NEWS_DIVISION, 0);
body.put(NEWS_ACCOUNT, account);
} catch (JSONException e) {
e.printStackTrace();
}
StringRequest request = new StringRequest(Request.Method.POST, GET_NEWS, new Response.Listener<JSONObject>() {
#Override
public void onResponse(String response) {
Log.i(TAG, response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + getMessage(error, context));
Toast.makeText(context, getMessage(error, context), Toast.LENGTH_SHORT).show();
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
return body.toString().getBytes();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type","application/json");
return headers;
}
};
queue.add(request);
But this code always returns "Bad request error"
Some things I've tried:
Override getParams() method instead of getBody(). (Didn't work)
Send a JSONObjectRequest with the body on the constructor. This one worked, but because my web service returns a String value I always get a ParseError. That's why I'm using StringRequest.
Any help is very much appreciated.
As already mentioned on njzk2's comment, the easiest way is to override getBodyContentType() instead. Overriding getHeaders() could probably work too, but you need to put all necessary headers, not only Content-Type, since you basically override the headers that the original method set.
Your code should look like this:
StringRequest request = new StringRequest(...) {
#Override
public byte[] getBody() throws AuthFailureError {
return body.toString().getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
};

Categories

Resources