I used Volley to POST name, password and email of a user for registration purpose. I took reference from This tutorial. And worked same as defined in this tutorial.
Here is my code:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
URL_string.api_url,null
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i("Result", "Success");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("Result", "UnSuccess");
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
Log.i("Result_Params",emailValue + passwordValue + nameValue);
params.put("email", emailValue);
params.put("password", passwordValue);
params.put("name", nameValue);
return super.getParams();
}
#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 super.getHeaders();
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjectRequest);
But my code shows this error:
[368] BasicNetwork.performRequest: Unexpected response code 422 for http://myapi.com/api/register
Error 422 is defined on the API as:
{
"message": "422 Unprocessable Entity",
"errors": {
"email": [
"The email field is required."
],
"password": [
"The password field is required."
],
"name": [
"The password field is required."
]
},
"status_code": 422
}
I tried:
changing JsonObjectRequest to StringRequest,
the original URL at the place of URL_string.api_url,
But the response is still same. Is this because of I didn't make any class for Volley library? I did that too from Androidhive.info, but failed!
I don't know how to go ahead from this step now, while Log in getParams logs the correct value of name, email, and pw entered by the user, but still POST operation is not working. Please help!
Thanks in advance!
You need to return the params object you create, not returning the parent's method (which is empty).
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
Log.i("Result_Params",emailValue + passwordValue + nameValue);
params.put("email", emailValue);
params.put("password", passwordValue);
params.put("name", nameValue);
return params; //not super.getParams();
}
As pointed out by pablobu, this also applies to your getHeaders():
#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; //not super.getHeaders();
}
Related
Hi All I am using Volley and trying to parse data from SOAP api. Following is my snippet code, when I try to parse data it is giving error. Can any one help me with this? I am getting following error every time.
E/Volley: [7440] BasicNetwork.performRequest: Unexpected response
code 400 for
public void HttpPOSTRequestWithParam() {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://www.myweb.co.ke/Wt/webtask.asmx?op=GetProductListing";
StringRequest postRequest = new StringRequest(Request.Method.POST, 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 => "+error.toString());
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("UserName", "John");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("User Name", "1234");
params.put("Password", "4321");
return params;
}
};
queue.add(postRequest);}
You may need to tell it how the Content-Type and Accept headers are encoded. Here the parameter string should look like:
'grant_type=password&username=apikey&password=apipassword'
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", "apikey");
params.put("password", "apipassword");
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;
}
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.
I google and I tried to post string request by attaching headers. But I always get auth failure error.It seems my header is not setting properly. Here is my code
StringRequest stringRequest = 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) {
if (error!=null){
error.printStackTrace();
}
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("client_id=",getString(R.string.client_id));
params.put("&client_secret=",getString(R.string.client_secret));
params.put("&grant_type=","authorization_code");
params.put("&code=",accessToken);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Basic " + base64);
params.put("Content-Type", "application/x-www-form-urlencoded");
params.put("Accept", "*/*" );
return super.getHeaders();
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
I attached headers in getHeaders() and stream writer in getParams().Can somebody help me to resolve this.Thanks in advance.
Dont put params like this
params.put("&grant_type=","authorization_code");
replace like this
params.put("grant_type", authorization_code);
Dont add & and = sign it will automatically included.
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("client_id",getString(R.string.client_id));
params.put("client_secret",getString(R.string.client_secret));
params.put("grant_type","authorization_code");
params.put("code",accessToken);
return params;
}
try header like this
#Override
public Map getHeaders() throws AuthFailureError {
Map headers = new HashMap();
headers.put("appId", "MYAPP_ID_HERE");
return headers;
}
Anyone know how to send post request with raw data in android volley ..?
I want to post this array list with headers.
[{
"Name": "qwertytestinggfgfgf"
}]
Here is my code:
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "my Authorization code is here ");
return headers;
}
#Override
protected Map<String, String> getParams() {
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", "rahatamjid");
return params;
}
Here is a screen shot.
headesr section is working good.
You better send request with json like this:
JsonRequest<JSONObject> jsonRequest = new JsonObjectRequest(Method.POST,httpurl, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "response -> " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, error.getMessage(), error);
}
})
{
#Override
public Map<String,String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "my Authorization code is here ");
return headers;
}
};
please try this and let me know:
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
String creds = String.format("%s:%s","USERNAME","PASSWORD"); //please adapt this to your auth type
String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.DEFAULT);
params.put("Authorization", auth);
params.put("Content-Type", "application/json");//
return params;
}
Override getBodyContentType to jsonBody in jsonObjectRequest method
#Override
public String getBodyContentType() {
return "application/json;charset=UTF-8";
}
then put your raw data in json object with key.
the root object should be jsonObject to post.It should not be json array
JSONObject jsonObject = new JSONObject();
jsonObject.put("yourKey",value);
Add more to Hashmap
Try like this,
#Override
protected Map<String, String> getParams() {
HashMap<String, String> params = new HashMap<String, String>();
params.put("name1", "rahatamjid1");
params.put("name2", "rahatamjid2");
params.put("name3", "rahatamjid3");
params.put("name4", "rahatamjid4");
Log.i("request","" + params);
return params;
}
This may helps you.
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