I am working on volley library: http://developer.android.com/training/volley/index.html
Get and 'Post methods without parameters' working fine. But when parameters are given, volley does not execute the form, and acts like form itself is a jsonObject:
com.android.volley.ParseError: org.json.JSONException: Value Login< of type java.lang.String cannot be converted to JSONObject
I have tried both overriding getParams() method:
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
return params;
}
And instantiating the object with parameter:
Map<String, String> params2 = new HashMap<String, String>();
params2.put("username", username);
params2.put("password", password);
JsonObjectRequest jsonObjectRequest1 = new JsonObjectRequest(Request.Method.POST, LOGIN_URL, new JSONObject(params2), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//onResponse
}
});
None of them worked. I am guessing my problem is about the content types. Volley library uses application/json while my php codes use name-value pairs.
I have seen these two questions but sadly they did not solve my case:
Google Volley ignores POST-Parameter
Volley Post JsonObjectRequest ignoring parameters while using getHeader and getParams
When you use JsonObjectRequest, you are saying that the content you are posting is a JSON Object and the response you expect back will also be a JSONObject. If neither of these are true, you need to build your own Request<T> and set the values you need.
The error you are seeing is because the response from the server is not a valid JSON response.
Related
JSON response from a remote server
{"status":"success",
"data":{"auth_token":"9389e656c90e11c451443657c8e",
"user":{"active_location":" Airport"}}}
I need to store the auth_token and pass to the remote server as the header,
tried addHeader("key1", "value1");
but still not working, need help
To send headers for belly request, you need to override getHeaders() method. Inside method create a map and put your key-value pairs and return the the map.
JsonObjectRequest request = new JsonObjectRequest(requestMethod, yourUrl, postData(if any), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//TODO parse your response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//TODO handle error
}
}){
//Here is the place where you can add your headers
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("key1", "value1");
return params;
}
};
Also if you need to pass any request parameters you can do that in the same way by overriding getParams() method.
For more details check the volley tutorial
You can simply use Base64 to encode the token string and put it in SharedPrefs, then read and decode to send in a header.
I am getting HTTP error 422, while making a DELETE request using volley. But, I am able to success response when I make request on Postman. Also, when I tried with HTTPConnection again got the same error.
Here is my code of volley request
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.DELETE, SERVER_URL,
postPropertyJSONObject, responseListener, errorListener);
you can refer https://github.com/ngocchung/DeleteRequest for long term solution, as it looks from documentation, but I have not tested this. A quick work arrount is to, to make request as post and then overwrite the header X-HTTP-Method-Override as DELETE.
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, SERVER_URL,postPropertyJSONObject, responseListener, errorListener);
and then add Header like this
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String> ();
headers.put("X-HTTP-Method-Override", "DELETE");
headers.put("Accept", "application/json");
headers.put("Content-Type", "application/json");
return headers;
}
I am doing an update on the old project & I don't have much knowledge of Android as of now. In project we have Comments section on product.
For comment after sending earlier we had return as 0 (some error) & 1 (success).
Below is the code we were using.
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Method.POST,
act.getString(R.string.CommentForUserURL),
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(
JSONObject response) {
Log.d("response done", "done===" + response);
mloading.setVisibility(View.GONE);
if (response != null) {
Comment obj = new Comment();
JSONObject jsonObject = response;
try {
obj.setComment(jsonObject
.getString("Comment"));
Now we have changed the return object from 0/1 to user object.
Does this need need to update JsonObjectRequest to GJSON request? Or object will also get parsed with JsonObjectRequest?
I am asking because when I execute above, I get error as below.
01-25 12:30:21.754: E/Volley(16487): [10114] BasicNetwork.performRequest:
Unexpected response code 500 for
http://new.souqalharim.com/add/CommentForMerchant
Any idea why I am getting this error?
Note: This URL is working fine for iPhone application.
Edit 1
This is post method, so full url is not there. There are few more parameters to add like ?comment=MyComment&userId=123&productId=234. As it is post I am not adding parameters in actual url.
I have those in another methods
#Override
protected Map<String, String> getParams()
throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("productId", productId.toString());
params.put("userId",
mSessionManager.getUserCode().toString());
params.put("comment", GlobalFunctions
.EncodeParameter(med_comments
.getText().toString()));
return params;
}
Full url is as below.
http://new.souqalharim.com/add/CommentForUser?productId=325&userId=5&comment=abcd
I tested this in Mozilla RESTClient and it works fine.
Edit 2
After checking further I found protected Map<String, String> getParams() throws AuthFailureError { is not getting called. Any idea why this is happening?
The problem is below.
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Method.POST,
act.getString(R.string.CommentForUserURL),
null, new Response.Listener<JSONObject>() {
^^^^
It should be
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Method.POST,
act.getString(R.string.CommentForUserURL),
new JSONObject(params), new Response.Listener<JSONObject>() {
^^^^^^^^^^^^^^^^^^^^^^
Copy code from protected Map<String, String> getParams() before final JsonObjectRequest.
That's it!!!
Reason is as below.
The JsonObjectRequest is extended JsonRequest which override getBody() method directly, so your getParam() would never invoke, I recommend you extend StringRequest instead of JsonObjectRequest.
your can check this answer for more details.
Actually 500 means Internal server error and this is caused by the Rest-api you are calling and not due to Volley,so check the back-end code.
BasicNetwork.performRequest: Unexpected response code 500
The server receives the correct response, but detects an error, this error is due to the PHP connection file with the database, this code must have the function implemented to hide the values of the query to avoid sql insertion
use this sample code:
<?php
$con = new mysqli('localhost', 'u648230499_wololo', '*********', 'u648230899_ejexample');
if ($con->connect_error) {
echo 'error connect database: ', $con->connect_error;
exit();
}
$participantId = $_POST['participantId'];
$name = $_POST['name'];
$sql = $con->prepare('INSERT INTO participant VALUES (?,?)');
$sql->bind_param('is', $participantId, $name);
$sql->execute();
echo 'OK\n';
$con->close();
?>
How do I send a DELETE Request using Volley (Android) to a REST Api with parameters like access_token and username. I have tried almost everything on Internet but still I am getting a 400 error Message.
I have tried sending the same DELETE request using PostMan and it works perfectly fine.
Here is the Error:
E/Volley﹕ [1112] BasicNetwork.performRequest: Unexpected response code 400 for http://myserverip/messages/2
and Here is the Java code that I am using:
String URI = "http://myserverip/messages/2";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.DELETE,URI,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(contextm,response.toString(),Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
headers.put("access_token", "access_token");
headers.put("username", "username");
return headers;
}
};
MyApp.getInstance().addToRequestQueue(request);
Might not be really useful but here is the working DELETE request preview from PostMan
DELETE /messages/1 HTTP/1.1
Host: serveripaddress
Cache-Control:no-cache
Content-Type: application/x-www-form-urlencoded
access_token=SPAVYaJ7ea7LzdeQYrBTsIRssuGbVpJI8G9XSV0n&username=whit3hawks
You can easily achieve this if you put the following instead of null in ... new JsonObjectRequest(Request.Method.DELETE,URI,null,new Response.Listener<JSONObject>() { ...
final JSONObject object = new JSONObject();
try {
object.put("access_token", "SPAVYaJ7ea7LzdeQYrBTsIRssuGbVpJI8G9XSV0n");
object.put("username", "whit3hawks");
} catch (Exception e) {
e.printStackTrace();
}
So your Request should look like this:
... new JsonObjectRequest(Request.Method.DELETE,URI,object,new Response.Listener<JSONObject>() { ...
You posted a long time ago, but maybe someone else will need this some time.
I am successfully sending headers in volley while using DELETE with this code:
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
just tried it and works like a charm.
EDIT:
if you're using a Mac, try checking with Charles what exactly it is you are sending,
on a PC you can try fiddler.
also, error 400 means 'Bad Input', so the server is either getting more info then it should, or less then he expects.
and keep in mind that DELETE in Volley acts as a GET, make sure you are sending an empty body with the request.
hope that helped somehow.. happy coding
I am trying to POST a JSON body using Volley in Android and after spending many hours with no success I am writing this question.
Following is mine code snippet
StringRequest residentSyncRequest = new StringRequest(Request.Method.POST, Commons.URL,this,this,ADD_REQ){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/json");
return params;
}
#Override
public byte[] getBody() throws AuthFailureError {
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(Commons.PREF_NAME, Context.MODE_PRIVATE);
try {
jsonObject.put("RowID","0");
jsonObject.put("LocalID","100");
jsonObject.put("LoginUserID",sharedPreferences.getString(Commons.pref_loginUserId,""));
jsonObject.put("AppToken",sharedPreferences.getString(Commons.pref_appToken,""));
} catch (JSONException e) {
e.printStackTrace();
}
jsonArray.put(jsonObject);
return jsonArray.toString().getBytes();
}
};
VollyRequest.getRequestQueue(getActivity()).add(residentSyncRequest);
and I am getting following response
E/Volley﹕ [255] BasicNetwork.performRequest: Unexpected response code 400 for ...
I tried to call the same web service using postman chrome extension and the service is working just fine.
Not sure if I need to do any encoding before returning byte[].
Please help.
Thanks in advance.
Volley doesn't support JsonArray request directly like JsonObject request.Hope they can add this function in next version because there are a lot of api only provide JsonArray.
EDIT:
Actually there is a solution here.
Volley by default puts all post parameters as JSON Values, so you just need to use a Request and not StringRequest and just add all JSON Values you want to post as regular post values.