Send parameters via POST method in Android - android

I am developing an Android App
The below mentioned is the link .
"http://example.com.in/ai/abc?var="+var
where var is a variable where result has come.I want to post the data available in the var along with the link . I am new to android so I want to know How to do POST method in Android App.

You should do something like this:
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}

You can use Android Volley Library to post your data to your php script.Here is the example of Volley Request
//Declare the URL you want to send
public static String YOUR_URL = "http://example.com.in/ai/abc?var=";
private void postDataToServer() {
//volley request
//here you can choose your method,GET/POST,in this case is Post
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.POST,
YOUR_URL , null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//if send data success do something here
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//if having error to make request to server do something here
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//send your parameter here
Map<String, String> parameters = new HashMap<>();
parameters.put("yourVariable", "var");
return parameters;
}
//adding header to authenticate
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonReq);
}
You can look at this tutorial to see how to post data from Android and get the data in your php script.

Related

how NOT to escape slashes, sending POST request using volley

I am sending POST request using volley. Request has custom headers and json request body. One of the json values in request body is a URL. When i create a jsonobject the // in URL is sent as \/\/. (e.g. "key1:"http//www.xyz.com" is sent as "key1":"http:\/\/www.xyz.com"
This causes a 400 error. How do i fix this?
Here is the POST using volley:
RequestQueue queue = Volley.newRequestQueue(this);
try{
jsonBody = new JSONObject();
jsonBody.put("Key1","http://xyz1.com");
jsonBody.put("Key2","val2");
}
catch (JSONException e){
}
JsonObjectRequest req = new JsonObjectRequest(Request.Method.POST,URL, jsonBody,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// handle response
Log.d("MAIN","response recd="+response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// handle error
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("CUSTOM_HEADER", "Yahoo");
headers.put("ANOTHER_CUSTOM_HEADER", "Google");
return headers;
}
};
queue.add(req);
The json values were correctly formatted. Checked by priting jsonbody.get("key")
the slashes are escaped when printing out the json using .toString.
For my case, the 400 error was fixed by adding header:
params.put("Content-Type","application/json; charset=utf-8");

errror in sending data to server using json object

i want to send some data to server on a specific url in json format but is not working. my json format is
JSON Object﹕ {"appt_email":"grddgf#ffgh.com","appt_service":"Test services 11","appt_contact":"8554688564","appt_time":"18.44","appt_name":"fddvnhff","appt_date":"18\/9\/2015"}
i am using Chrome Poster extension to test it. when i use it the data is sent properly. bt when i send from application it is not working.
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(
"http://tipseducation.com/system/eadmin/insertschedule/");
httpRequest.setHeader("Content-Type", "application/json");
JSONObject json = new JSONObject();
//StringEntity se = new StringEntity(json.toString()); httpRequest.setEntity(se); httpRequest.setHeader("Accept", "application/json");
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding("UTF-8");
se.setContentType("application/json");
json.put("appt_name", ed_name);
json.put("appt_email", ed_email);
json.put("appt_contact", ed_contact);
json.put("appt_date", ed_date);
json.put("appt_time", ed_time);
json.put("appt_service", ed_spinner);
}
I would use String Request.
StringRequest sr = new StringRequest(type, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Valid Response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//error message
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("appt_name", ed_name);
params.put("appt_email", ed_email);
params.put("appt_contact", ed_contact);
params.put("appt_date", ed_date);
params.put("appt_time", ed_time);
params.put("appt_service", ed_spinner);
return params;
}
};

Volley JsonObjectRequest Post parameters no longer work

I am trying to send POST parameters in a Volley JsonObjectRequest. Initially, it was working for me by following what the official code says to do of passing a JSONObject containing the parameters in the constructor of the JsonObjectRequest. Then all of a sudden it stopped working and I haven't made any changes to the code that was previously working. The server no longer recognizes that any POST parameters are being sent. Here is my code:
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://myserveraddress";
// POST parameters
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "test");
JSONObject jsonObj = new JSONObject(params);
// Request a json response from the provided URL
JsonObjectRequest jsonObjRequest = new JsonObjectRequest
(Request.Method.POST, url, jsonObj, new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
});
// Add the request to the RequestQueue.
queue.add(jsonObjRequest);
Here is the simple tester PHP code on the server:
$response = array("tag" => $_POST["tag"]);
echo json_encode($response);
The response I get is {"tag":null}
Yesterday, it worked fine and was responding with {"tag":"test"}
I haven't changed a single thing, but today it is no longer working.
In the Volley source code constructor javadoc it says that you can pass a JSONObject in the constructor to send post parameters at "#param jsonRequest":
https://android.googlesource.com/platform/frameworks/volley/+/master/src/main/java/com/android/volley/toolbox/JsonObjectRequest.java
/**
* Creates a new request.
* #param method the HTTP method to use
* #param url URL to fetch the JSON from
* #param jsonRequest A {#link JSONObject} to post with the request. Null is allowed and
* indicates no parameters will be posted along with request.
I have read other posts with similar questions, but the solutions haven't worked for me:
Volley JsonObjectRequest Post request not working
Volley Post JsonObjectRequest ignoring parameters while using getHeader and getParams
Volley not sending a post request with parameters.
I've tried setting the JSONObject in the JsonObjectRequest constructor to null, then overriding and setting the parameters in the "getParams()", "getBody()", and "getPostParams()" methods, but none of those overrides has worked for me. Another suggestion was to use an additional helper class that basically creates a custom request, but that fix is a bit too complex for my needs. If it comes down to it I will do anything to make it work, but I am hoping that there is a simple reason as to why my code was working, and then just stopped, and also a simple solution.
You just have to make a JSONObject from your HashMap of parameters:
String url = "https://www.youraddress.com/";
Map<String, String> params = new HashMap();
params.put("first_param", 1);
params.put("second_param", 2);
JSONObject parameters = new JSONObject(params);
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, parameters, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//TODO: handle success
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
//TODO: handle failure
}
});
Volley.newRequestQueue(this).add(jsonRequest);
I ended up using Volley's StringRequest instead, because I was using too much valuable time trying to make JsonObjectRequest work.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://myserveraddress";
StringRequest strRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "test");
return params;
}
};
queue.add(strRequest);
This worked for me. Its just as simple as JsonObjectRequest, but uses a String instead.
I had a similar problem, but I found out that the problem was not on the client side, but in the server side. When you send a JsonObject, you need to get the POST object like this (in the server side):
In PHP:
$json = json_decode(file_get_contents('php://input'), true);
You can use StringRequest to do the same things you can wtih JsonObjectRequest, while still beeing able to easily send POST parameters. The only thing you have to do is to create a JsonObject out of the request String you get, and from there you can continue as if it were JsonObjectRequest.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//Creating JsonObject from response String
JSONObject jsonObject= new JSONObject(response.toString());
//extracting json array from response string
JSONArray jsonArray = jsonObject.getJSONArray("arrname");
JSONObject jsonRow = jsonArray.getJSONObject(0);
//get value from jsonRow
String resultStr = jsonRow.getString("result");
} catch (JSONException e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> parameters = new HashMap<String,String>();
parameters.put("parameter",param);
return parameters;
}
};
requestQueue.add(stringRequest);
Use CustomJsonObjectRequest helper class mentioned here.
and implement like this -
CustomJsonObjectRequest request = new CustomJsonObjectRequest(Method.POST, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getActivity(), response.toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error.", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("id", id);
params.put("password", password);
return params;
}
};
VolleySingleton.getInstance().addToRequestQueue(request);
Using the JSONObject object to send parameters means the parameters will be in JSON format in the HTTP POST request body :
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "test");
params.put("tag2", "test2");
JSONObject jsonObj = new JSONObject(params);
Will create this JSON object and insert it into the body of the HTTP POST request:
{"tag":"test","tag2":"test2"}
Then the server must decode the JSON to understand these POST parameters.
But normally HTTP POST paramaters are write in the body like:
tag=test&tag2=test2
But NOW here the question is why Volley is set in this manner?
A server reading a HTTP POST method should by standard always try to read parameters also in JSON (other than in plain text) and so a server that does not accomplish is a bad server?
Or instead a HTTP POST body with parameters in JSON is not what normally a server want?
Might help someone and save you some time thinking.
I had a similar issue, the server code was looking for the Content-Type header. It was doing it this way:
if($request->headers->content_type == 'application/json' ){ //Parse JSON... }
But Volley was sending the header like this:
'application/json; charset?utf-8'
Changing the server code to this did the trick:
if( strpos($request->headers->content_type, 'application/json') ){ //Parse JSON...
I had similar problem. But I found out that the problem was not on the server side, but the problem is about cache. You have to clear your RequestQueue Cache.
RequestQueue requestQueue1 = Volley.newRequestQueue(context);
requestQueue1.getCache().clear();
You can do it this way:
CustomRequest request = new CustomRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Toast.makeText(SignActivity.this, response.toString(), Toast.LENGTH_SHORT).show();
Log.d("response",""+response.toString());
String status = response.optString("StatusMessage");
String actionstatus = response.optString("ActionStatus");
Toast.makeText(SignActivity.this, ""+status, Toast.LENGTH_SHORT).show();
if(actionstatus.equals("Success"))
{
Intent i = new Intent(SignActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
dismissProgress();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SignActivity.this, "Error."+error.toString(), Toast.LENGTH_SHORT).show();
Log.d("response",""+error.toString());
dismissProgress();
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Email", emailval);
params.put("PassWord", passwordval);
params.put("FirstName", firstnameval);
params.put("LastName", lastnameval);
params.put("Phone", phoneval);
return params;
}
};
AppSingleton.getInstance(SignActivity.this.getApplicationContext()).addToRequestQueue(request, REQUEST_TAG);
as per CustomRequest below link
Volley JsonObjectRequest Post request not working
It does work.
I parsed json object response using this:-
works like a charm.
String tag_string_req = "string_req";
Map<String, String> params = new HashMap<String, String>();
params.put("user_id","CMD0005");
JSONObject jsonObj = new JSONObject(params);
String url="" //your link
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, jsonObj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("responce", response.toString());
try {
// Parsing json object response
// response will be a json object
String userbalance = response.getString("userbalance");
Log.d("userbalance",userbalance);
String walletbalance = response.getString("walletbalance");
Log.d("walletbalance",walletbalance);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
AppControllerVolley.getInstance().addToRequestQueue(jsonObjReq, tag_string_req);
It worked for me can try this for calling with Volley for Json type request and response .
public void callLogin(String sMethodToCall, String sUserId, String sPass) {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST, ConstantValues.ROOT_URL_LOCAL + sMethodToCall.toString().trim(), addJsonParams(sUserId, sPass),
// JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, object,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("onResponse", response.toString());
Toast.makeText(VolleyMethods.this, response.toString(), Toast.LENGTH_LONG).show(); // Test
parseResponse(response);
// msgResponse.setText(response.toString());
// hideProgressDialog();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("onErrorResponse", "Error: " + error.getMessage());
Toast.makeText(VolleyMethods.this, error.toString(), Toast.LENGTH_LONG).show();
// hideProgressDialog();
}
}) {
/**
* 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;
}
};
requestQueue.add(jsonObjectRequest);
}
public JSONObject addJsonParams(String sUserId, String sPass) {
JSONObject jsonobject = new JSONObject();
try {
// {"id":,"login":"secretary","password":"password"}
///***//
Log.d("addJsonParams", "addJsonParams");
// JSONObject jsonobject = new JSONObject();
// JSONObject jsonobject_one = new JSONObject();
//
// jsonobject_one.put("type", "event_and_offer");
// jsonobject_one.put("devicetype", "I");
//
// JSONObject jsonobject_TWO = new JSONObject();
// jsonobject_TWO.put("value", "event");
// JSONObject jsonobject = new JSONObject();
//
// jsonobject.put("requestinfo", jsonobject_TWO);
// jsonobject.put("request", jsonobject_one);
jsonobject.put("id", "");
jsonobject.put("login", sUserId); // sUserId
jsonobject.put("password", sPass); // sPass
// js.put("data", jsonobject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return jsonobject;
}
public void parseResponse(JSONObject response) {
Boolean bIsSuccess = false; // Write according to your logic this is demo.
try {
JSONObject jObject = new JSONObject(String.valueOf(response));
bIsSuccess = jObject.getBoolean("success");
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(VolleyMethods.this, "" + e.toString(), Toast.LENGTH_LONG).show(); // Test
}
}
Hope am not too late to the party:
The issue is from the server side. If you are using PHP add the following lines at the top of your php api file (after includes)
$inputJSON = file_get_contents('php://input');
if(get_magic_quotes_gpc())
{
$param = stripslashes($inputJSON);
}
else
{
$param = $inputJSON;
}
$input = json_decode($param, TRUE);
Then to retrieve your values
$tag= $input['tag'];
Use GET in place of POST for using JsonObjectRequest
VolleySingleton.getInstance()
.add(new StringRequest(Request.Method.POST, urlToTest, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// do stuff...
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// exception
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
protected Map<String, String> getParams() {
return ServerApi.getRequiredParamsRequest(context);
}
}
);
...Initially, it was working for me
....Then all of a sudden it stopped working and I haven't made any changes to
the code
if you haven't made any changes to a previously working code then I suggest checking other parameters such as URL , as the IP address may change if you are using your own Computer as a server!

Put request using volley

I am trying to update data on server by using PUT method but I am getting this error , I haven't used volley before ,Is there anything I am missing ? please suggest .
My code :
private void sendRequest() {
RequestQueue queue = Volley.newRequestQueue(getActivity());
PersonalInfoModel.Data.PersonalInformation.Address address;
address = new PersonalInfoModel().new Data().new PersonalInformation().new Address();
address.setBuilding("test");
address.setCountry("test");
address.setCounty("test");
address.setPostcodeInCode("");
address.setPostcodeOutCode("");
address.setTown("");
PersonalInfoModel.Data.PersonalInformation data;
data = new PersonalInfoModel().new Data().new PersonalInformation();
data.setDob("tsst");
data.setEmail("testemai");
data.setForename("test");
data.setSurname("data");
data.setAddress(address);
Gson gson = new Gson();
JSONString = gson.toJson(data);
try {
obj = new JSONObject(JSONString);
} catch (JSONException e) {
e.printStackTrace();
}
LogUtils.LOGD(TAG, "JSONString is :: " + JSONString.toString());
JsonObjectRequest putRequest = new JsonObjectRequest(Request.Method.PUT, urlUserDetail, obj,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
// response
LogUtils.LOGD("Response", response.toString());
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
LogUtils.LOGD("Error.Response", error.toString());
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("tess", "2222");
params.put("Authorization", "def1bc98d032");
params.put("Content-Type", "application/json; charset=utf-8");
return params;
}
#Override
public byte[] getBody() {
try {
LogUtils.LOGD("json", obj.toString());
return obj.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
};
queue.add(putRequest);
}
Error :
BasicNetwork.performRequest: Unexpected response code 400 for url
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("tess", "2222");
params.put("Authorization", "def1bc98d032");
// add this parameter
params.put("Content-Type", "application/json; charset=utf-8");
return params;
}
Check with PostMan or some client and check if you are getting a right response back and eliminate that possibility - the request works without using android volley
Response code 400 means Bad request. It means that the request you're making is incorrect. Possibly the content type has an error, try adding
params.put("Content-Type", "application/json; charset=utf-8"); to getHeaders()
try removing the getbody method.. because you are sending the request parameters as a json object and content type header is also application/json.so getbody won't be necessary
JsonObjectRequest adds Content-Type: application/json; charset=utf-8 by default. Your params.put("Content-Type", "application/json; charset=utf-8"); adds another Content-Type and some applications don't work with multiple Content-Type definitions. You should try to remove params.put("Content-Type", "application/json; charset=utf-8");.
Make sure that the request URL for a PUT request has the id of the resource as the last path segment. Otherwise you will get a 404.
Wrong form of URL:
/users
Correct form of URL:
/users/bob

Volley POST request, 400 error

This is the first time I'm working with JSON but I'm experimenting with POST requests.
I want to make a POST request to this website http://jsonblob.com/api
My code works when I use an asynctask + httppost
private static final String url = "http://jsonblob.com/api/jsonBlob";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new PostJsonTask().execute();
}
private class PostJsonTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
HttpResponse response = post();
Header s = response.getFirstHeader("Location");
Log.d("PostJsonTask", s.getValue());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private HttpResponse post() throws Exception {
// convert parameters into JSON object
Map<String, String> params = new HashMap<String, String>();
params.put("user", "Robby");
params.put("pass", "zqdqzdqdqzd");
JSONObject holder = new JSONObject(params);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
StringEntity se = new StringEntity(holder.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
post.setEntity(se);
return client.execute(post);
}
}
With this code I can succesfully get the Location parameter.
But I want to do this with the Volley library, I already have the following code :
private static final String url = "http://jsonblob.com/api/jsonBlob";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST, url, createResponseListener(), createErrorListener()) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
headers.put("Content-type", "application/json");
return headers;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("user", "Robby");
params.put("pass", "zqdqzdqdqzd");
return params;
}
#Override
protected Response<String> parseNetworkResponse(
NetworkResponse response) {
Map<String, String> headers = response.headers;
String location = headers.get("Location");
Log.d("PostJsonTask", location);
return super.parseNetworkResponse(response);
}
};
queue.add(request);
}
private ErrorListener createErrorListener() {
return new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
};
}
private Listener<String> createResponseListener() {
return new Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("PostJsonTask", response);
}
};
}
But this returns a VolleyError with code 400. How can I fix this?
Instead of trying to set Content-type of header try to set for bodyContentType and in postman(web) also you are setting the content type of body only
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
url, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.toString());
}
})
#Override
public String getBodyContentType() {
return "application/json";
}
};
Don't use the getParams override.
Instead, create a JSON with these parameter and provide as the body of the request like they do in JsonObjectRequest (or just use a JsonObjectRequest instead of a StringRequest), e.g.
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("user", "Robby");
jsonObject.put("pass", "zqdqzdqdqzd");
} catch (JSONException e) {
// handle exception (not supposed to happen)
}
StringRequest request = new StringRequest(Request.Method.POST, url, createResponseListener(), createErrorListener()) {
// your code without getParams
#Override
public byte[] getBody() {
try {
return jsonObject.toString.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
// not supposed to happen
return null;
}
}
}

Categories

Resources