Android Volley Post with Map<String, Object> params (?) - android

I have been trying to post my Credentials class from Android to C#.Net web server.
Volley Post method accepts params like:
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return parameters;
}
Return type of getParams() is Map<String, String> but I need Map<String, Object> to send my class to web server. I even tried to convert my class into json string like:
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("credentials", new Gson().toJson(mCredentials, Credentials.class));
return parameters;
}
But it does not work. Server returns "Invalid Parameter" error which is thrown when "credentials" parameter is null.
There is nothing wrong on server side because I was able to do it with AsyncTask. I decided to turn my requests into Volley and I got stuck on this problem.
Anybody has a solution?

This is how I do it (note: params is a jsonobject, not a map):
//fill params
JSONObject params = new JSONObject();
params.put("username", username);
params.put("password", password);
//create future request object
RequestFuture<JSONObject> future = RequestFuture.newFuture();
//create JsonObjectRequest
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, URL, params, future, future);
//add request to volley
MyVolley.getRequestQueue().add(jsObjRequest);
//pop request off when needed
try {
JSONObject response = future.get();//blocking code
} catch (Exception e) {
e.printStackTrace();
}

If you need to have your package send something like an object, you can put a JSONObject within a JSONObject. Eg
JSONObject outer = new JSONObject();
JSONObject inner = new JSONObject();
inner.put("first_name","James");
inner.put("last_name","Bond");
outer.put("person",inner);
outer.put("id","1");

Related

Android Volley request failing

I am attempting a Volley request through android to get Oauth credentials using a password grant type. What I am trying works in postman, but is not working in android and I am not sure what I am doing wrong. Below please find the code I am using:
final RequestQueue queue = Volley.newRequestQueue(this);
final String url = Constants.OAUTH_URL;
Map<String, String> body = new HashMap<>();
body.put("grant", "password");
final JSONObject jso = new JSONObject(body);
JsonObjectRequest postRequest = new JsonObjectRequest (Request.Method.POST, url, jso,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(final JSONObject response) {
//Do something
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
responseText.setText(error.toString());
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("accept", "application/vnd.TestKitchen.v1+json");
headers.put("Authorization", BasicAuth.getBasicAuth(Constants.USERNAME, Constants.PASSWORD));
headers.put("Content-Type", "application/json; charset=UTF-8");
return headers;
}
};
queue.add(postRequest);
My OAuth URL is correct, I have verified that several times. So the problem isn't a typo on that end. All of the other fields should still reach my server and give an appropriate response (Be it an error or not), however all requests I send are returning with a 400 response. Anything obvious I am doing wrong that I should fix? Any help is appreciated. Thanks.
Why are you using this thing?
Map<String, String> body = new HashMap<>();
body.put("grant", "password");
final JSONObject jso = new JSONObject(body);
You can directly put the value in JSONObject
JSONObject jso = new JSONObject();
jso.put("grant", "password");
In the case of a REST API with a JSON payload, 400's are typically, and correctly I would say, used to indicate that the JSON is invalid in some way according to the API specification for the service.

How to send POST request in JSON and response in JSON using volley (Android)

private void login(){
// Post params to be sent to the server
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", username);
params.put("password", password);
JsonObjectRequest req = new JsonObjectRequest(login_URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.v("Response:%n %s", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
}){
/**
* Passing some request headers
* */
#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;
}
};
// add the request object to the queue to be executed
AppController.getInstance().addToRequestQueue(req);}
I got below error:
E/Volley: [1] 10.onErrorResponse: Error:
i dont know where the problem
json send as post:
{
"":"",
"":"",
"":"",
}
json response as:
{"":""}
You should add the Request.Method.POST as the first parameter of your new JsonObjectRequest method. Also scrap out the new 'JSONObject(params)'.
Now override the getParams() method just above your getParams override and add the content of your login method there. You should return params.
It should work. Let me know if you have any challenges. :).
A very good example would be here
Volley library can be integrated using grader and if you want to know about implementation of Requests in volley then following link can give you all types of requests you can make with volley and how to implement it .
Here you go
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

Volley Post method gives me unexpected response code 400?

Here am new for android development am trying to post json value to server using gson lib i have converted into json but when i try to send to server is throws 400 unexpected response code here let me post my code:
listobj = account_sf_db.toServer();
Gson gson = new Gson();
RequestQueue queue = Volley.newRequestQueue(getBaseContext());
final String yog = gson.toJson(listobj);
String URL = "http://xxx.xx.xx.xxx/xxx/CRM/AcoountCreatePageLoad.svc/xxt/xxxt/ " +yog ;
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String resp = response.toString();
}
}, 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("god", yog);
return params;
} #Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Accept","application/json");
headers.put("User-agent", "My useragent");
return headers;
}
};
queue.add(stringRequest);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
400 status code is for Bad Request, it means server is not expecting this type of request.
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
Please check headers(content-type, user agent,etc.) you are adding whether it is required or not. It might happen that server is expecting a simple request and not json request.
Also try to read out error you get in onErrorResponse. Server might have responded you the expected parameter and request type, and also discuss the type of API developed by the web developer.
You have a space in your url after the /xxt/xxxt/
String URL = "http://xxx.xx.xx.xxx/xxx/CRM/AcoountCreatePageLoad.svc/xxt/xxxt/ " +yog ;
Remove it and I think you'll be fine.
P.S 400 generally means there is something wrong with the Url or parameters.

Volley Post JsonObjectRequest ignoring parameters while using getHeader and getParams

I am trying to connect API url="api adress" which accepts two header types application/json to reponce in json and application/xml to reponce in xml. I need to hit JSON with json parameters and responce will be in json format too. Using android volley Post request with JsonObjectRequest setting headers using getHeaders it connects to server but getParams to set parameters does not work.
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
Constants.BASE_URL + Constants.LOGIN, null, response,
response_error) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
#Override
protected Map<String, String> getPostParams()
throws AuthFailureError {
// TODO Auto-generated method stub
Map<String, String> params = new HashMap<String, String>();
params.put("key", "value");
return params;
}
};
// implementation of listeners
Response.Listener<JSONObject> response = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
Log.e("responce", response.toString());
// msgResponse.setText(response.toString());
hideProgressDialog();
}
};
Response.ErrorListener response_error = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error responce", error.getMessage());
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
};
//get params never get called
//i also tried alternative to send params but does not works.
Map<String, String> params = new HashMap<String, String>();
params.put("key", "value");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
Constants.BASE_URL + Constants.LOGIN, new JSONObject(params), response,
response_error) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
};
any type of help will be appretiated, Thanks in advance.
Volley will ignore your Content-Type setting, if you want to modify the content-type, you can override the getBodyContentType method :
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, url,
new JSONObject(params), response, response_error) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
}
for why volley ignore your parameters? take a look at my another answer.
Volley JsonObjectRequest Post request not working
Take the other answer from that post wich starts with: You can create a custom JSONObjectReuqest

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