I'm trying to send a Post request with volley without success.
The lib is working correctly, and I manage to sent some string requests, but the Post with a JsonObject doesn't work.
String urlJsonReq = "https://api.parse.com/1/classes/GameScore";
String tag_json_obj = "tag_json";
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.POST,
urlJsonReq,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("MyApp", response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("MyApp", "Error: " + error.getMessage());
// hide the progress dialog
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("value1", "testValue1");
params.put("value2", "testValue2");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("X-Parse-REST-API-Key", "xxxxxxxxxxxx");
headers.put("X-Parse-Application-Id", "xxxxxxxxxxx");
return headers;
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
I keep getting an error. I read somewhere, but without any details that the volley cannot sent JsonObjects, only receive then. That if you want to solve that problem you should implement an custom class, but I really don't know if I'm just making an stupid mistake here (it is possible).
Do you guys know something about that?
Thank you for your time.
You can send the JSONObject without overiding the getParams or getBodyContentType. Something like this for example
JSONObject object = new JSONObject();
JsonObjectRequest jr = new JsonObjectRequest(Request.Method.POST, url, object, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Obviously you can Override the headers if you need to.
Related
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¶m1=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;
}
};
Hi friends i am developing an App for Student Database Management System.
Below is code to make request to server for each user service request and server sends response as in Json fromat.
LoginActivity.java
onCreate(){
requestQueue = Volley.newRequestQueue(context);
//making service method call here
JSONObject json = makeRequest(url,loginJson);
//printing response given by makeRequest() method
Log.e("std","-----------------Inside onCreate()----------------------" );
Log.e("std"," requested json "+json );
}
//////
public JSONObject makeRequest(String url, JSONObject jsonObject){
JSONObject myjson;
JsonObjectRequest myReq = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("std","-----------------Inside onResponse()----------------------" );
Log.e("std","response \n"+response);
myJson = new JSONObject(String.valueOf(response))
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
error.printStackTrace();
Log.e("error"," onErrorResponse "+error);
Toast.makeText(context,"Server Error...",Toast.LENGTH_SHORT).show();
}
}){
#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(myReq);
return myJson;
}
inside onResponse listener i am getting my response as shown in bellow.
But makeRequest method returns me null JSON.
LogCat
com.example.stddbsystem E/std:-----------------Inside onResponse()----------------------
com.example.stddbsystem E/std:{"responseCode": 200,"responseMessage": "Login Success","userId": 1}
com.example.stddbsystem E/std:-----------------Inside onCreate()----------------------
com.example.stddbsystem E/std:requested json : null
Try this:
Change to:
#Override
public void onResponse(JSONObject response) {
myJson =response;
}
Instead of:
#Override
public void onResponse(JSONObject response) {
myJson = new JSONObject(String.valueOf(response))
}
I am trying to make an HTTPS request via POST with volley but it is not working. The request takes me to onErrorResponse but does not show what the error is. I tested with Postman and it works fine.
I leave part of my code.
Map<String, String> params = new HashMap<String, String>();
params.put(PARAM_HASH_TOKEN, HASH_TOKEN);
params.put(PARAM_USUARIO, id);
params.put(PARAM_PASSWORD, password);
JSONObject jsonBody = new JSONObject(params);
Log.e("POST",jsonBody.toString());
JsonObjectRequest mJsonObjectRequest = new JsonObjectRequest(Request.Method.POST, URL_API, jsonBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (response != null) {
F_PARSEAR_JSON_RESPUESTA(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String msg = (error.getMessage() == null) ? "Ha ocurrido un error, intentelo de nuevo." : error.getMessage();
Log.e("ERROR",URL_API);
Log.e("ERROR",msg);
_loginButton.setEnabled(true);
}
});
ApplicationLoader.getInstance().addToRequestQueue(mJsonObjectRequest);
Can you check Content type in client and server? They are similar value.
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
return headers;
}
#Override
public String getBodyContentType()
{
return "application/json";
}
I hope it will help you!
when i try to post json and take result as a json i get response code 500 error. But if i try this with string request there is no problem. I searched a lot on stackoverflow, there are other people like me having this problem but there is no up-to-date solution for this. So may anyone show me how i can do json object post request by up-to-date method(with also php side) please?
Android side:
Map<String, String> map = new HashMap<String, String>();
map.put("user", username);
map.put("pass", password);
JsonObjectRequest sr = new JsonObjectRequest(Request.Method.POST, "http://www.example.com/example/.php?action=signin", new JSONObject(map), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject result) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
return params;
}
};
PHP side:
$post = json_decode(file_get_contents("php://input"), true);
$user = $post['user'];
$pass = $post['pass'];
$array = array("entrance" => $example);
echo json_encode($array,true);
I fixed the problem, there was only one element in my json object which is a jsonarray actually. After i changed jsonobjectrequest to jsonarrayrequest, the problem was solved.
try this
JSONObject map = new JSONObject();
map.put("user", username);
map.put("pass", password);
JsonObjectRequest sr = new JsonObjectRequest(Request.Method.POST, "http://www.example.com/example/.php?action=signin", map, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject result) {
Log.e("ServiceCall", result.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ServiceCall", error.toString());
}
});
RequestQueue mRequestQueue = Volley.newRequestQueue(<Activity>.this);
mRequestQueue.add(sr);
i think you have problem with your json ..and thats why at the server
side it throws error and server error 500 comes
I am using Volley Library to make network calls and I am using it for the first time. I am trying to set a break point in onResponse method but the break point is getting toggled on JsonObjectRequest. Following is my code
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, urlL1, "", new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(CVLenderApp.TAG, response.toString());
// I would like to set the break point at this line
Toast.makeText(SignInActivity.this, "Success", 3000).show();
pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(CVLenderApp.TAG, "Error: " + error.getMessage());
pDialog.hide();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("userName", "name");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
};
// Adding request to request queue
CVLenderApp.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
I hope I'm doing a small mistake, but I'm unable to figure that out.
Thank you,
Anudeep Reddy.
As I commented, for POST request's parameters, override getBody instead of getParams
Moreover, if your project uses Google's official Volley, then try the following sample code:
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("userName", "name");
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// do something...
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something...
}
});
MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
Hope this helps!