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!
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;
}
};
I am trying hit an api(written in PHP) and posting params with it.
Here is my code:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, null,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("prerna succes volley "+response.toString());
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("prerna fail volley "+error.toString());
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> pars = new HashMap<String, String>();
pars.put("Content-Type", "application/x-www-form-urlencoded");
return pars;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("action", "login");
params.put("username", "abc#xyz.com");
params.put("pass", "a");
return params;
}
};
I always get invalid username/password which has been handled in api in case there is invalid username and password.In this case api is not receiving the params.
I tried to do it with retrofit and its working fine with it that means there is no problem at API coding. What am I missing here in case of volley?
Thanks for the support. I am able to solve the problem by changing JsonObjectRequest to StringRequest. i found Volley JsonObjectRequest Post parameters no longer work where I got to know that JsonObjectRequest creates some unexpected problems.
There is my code:
StringRequest jsonObjReq = new StringRequest(Request.Method.POST,
url,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response.toString());
String no = jsonObject.getString("$PhoneNo");
} catch (JSONException e) {
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("prerna fail volley " + error.toString());
}
})
{
#Override
public String getBodyContentType() {
Map<String, String> pars = new HashMap<String, String>();
pars.put("Content-Type", "application/x-www-form-urlencoded");
//return pars;
return "application/x-www-form-urlencoded";
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("action", "login");
params.put("username", "abc#xyz.com");
params.put("pass", "a");
return params;
}
};
However I am still trying to figure out why JsonobjectRequest did not work.
As far as I can tell by looking at JsonObjectRequest your 3rd parameter is null, and it indicates the JsonObject request - by the documentation "jsonRequest - A JSONObject to post with the request. Null is allowed and indicates no parameters will be posted along with request."
And after searching again, I saw this thread.
if you are sending your data in raw format you need to try this,first of all make json of your data to be post.
final JSONObject jsonBody = new JSONObject();
jsonBody.put("mobile", phoneNumber);
jsonBody.put("otp", otp.trim());
and you have to override these methods
#Override
public byte[] getBody() throws AuthFailureError {
return jsonBody.toString().getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
if you also have header in your post request you also send that with by following type
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
String auth_token = "bearer" + prefs.getPreferencesString(context, "AuthToken").toString();
params.put("Authorization", auth_token);
return params;
}
Here is the whole code.
final JSONObject jsonBody = new JSONObject();
jsonBody.put("mobile", phoneNumber);
jsonBody.put("otp", otp.trim());
StringRequest sr = new StringRequest(Request.Method.POST, Constraints.Base_URL + "/api/v1/verifyotp", new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
progressDialog.dismiss();
JSONObject jsonObject = new JSONObject(response);
int status = jsonObject.getInt("status");
String token = jsonObject.getString("token");
prefs.setPreferencesString(OtpActivity.this, "AuthToken", token);
if (status == 1) {
startActivity(new Intent(getApplicationContext(), WelcomeScreenActivity.class));
overridePendingTransition(R.anim.right_in, R.anim.left_out);
} else if (status == 0) {
Toast.makeText(OtpActivity.this, "Please Enter Otp!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(OtpActivity.this, "Invalid otp please try again!!", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
return jsonBody.toString().getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
MyApplication.getInstance().addToReqQueue(sr, "jreq");
}
} catch (Exception e) {
}
Try migrating to getHeaders and remove getParams
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("action", "login");
params.put("username", "abc#xyz.com");
params.put("pass", "a");
return pars;
}
Or - Reuse the getParams method
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = getParams();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
If it is a body request all you need to do is add the extra parameter.
JSONObject body = new JSONObject();
body.put("action", "login");
body.put("username", "abc#xyz.com");
body.put("pass", "a");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, body,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("prerna succes volley "+response.toString());
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("prerna fail volley "+error.toString());
}
});
I'm trying to send a JsonObjectRequest to my server with some params, but seems like params doesn't arrive at the server. Before to post on SO I try all kind of suggestion found in google but no one works fine..
This is the code of my JsonObjectRequest:
RequestQueue queue = MySingleVolley.getInstance(ctx).
getRequestQueue();
JsonObjectRequest jsObjRequest = new JsonObjectRequest(method,url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("REQUEST_JSON_TO_SERVER", "Success: " + response.toString());
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("REQUEST_JSON_TO_SERVER", "Error: " + error);
}
}){
#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> getParams() {
return params;
}
};
MySingleVolley.getInstance(ctx).addToRequestQueue(jsObjRequest);
And these are my param and others:
String url = "url";
//create the hashMap of parameters
database_zappapp db = new database_zappapp(getApplicationContext());
db.open();
HashMap<String, String> params = new HashMap<>();
params.put("action","myAction");
params.put("nomeutente", db.getUsernameLogged());
params.put("token", token);
db.close();
//Send the request to the server
Global.RequestJsonToServer(getApplicationContext(), url, Request.Method.POST, params);
Thanks in advance for the help!
Edit 2
I've changed my params in this creating a string jsonBody:
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("action","gcmUserRegister");
jsonObject.put("nomeutente",db.getUsernameLogged());
jsonObject.put("token",token);
}catch(JSONException e){
e.printStackTrace();
}
String requestBody = jsonObject.toString();
db.close();
and my request like this with getBody():
JsonObjectRequest jsObjRequest = new JsonObjectRequest(method,url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("REQUEST_JSON_TO_SERVER", "Success: " + response.toString());
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("REQUEST_JSON_TO_SERVER", "Error: " + error);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
return headers;
}
#Override
public byte[] getBody() {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
requestBody, "utf-8");
return null;
}
}
};
But already didn't work! =(
Postman screen:
No user found means that it enter in the if statement and so it works.. with android i receive "result": "null"
The postman screen with app/json:
I've found the solution!
The problem was in the server not in the client, I was getting the data using POST but from the client I was sending a json object so my new php is:
$data = json_decode(file_get_contents('php://input'), true);
//echo "Action: ".$action;
//Registrazione del token
if($data['action'] == "gcmUserRegister"){
......
Thanks al lot to BKS!!!
Change this part of your code:
`JsonObjectRequest jsObjRequest = new JsonObjectRequest(method,url,null ...`
To this:
`JsonObjectRequest jsObjRequest = new JsonObjectRequest(method,url,yourparams..`
Reason: if you are using the default Volley constructors thats the way to send params to Server.
I have an API endpoint which needs parameters to be sent as JsonObject in a POST request.
The response which I will get is not Json, but rather a small CSV string.
The Code is
stringRequest = new StringRequest(Request.Method.GET, "http://apitest.eezyrent.com/api/userauthentication/SignUp",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
Toast.makeText(getApplication(), response.toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplication(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> jsonParams2 = new HashMap<String, String>();
jsonParams2.put("vcFName", firstname.getText().toString());
jsonParams2.put("vcLname", lastname.getText().toString());
jsonParams2.put("vcMobileNo", phone_no.getText().toString());
jsonParams2.put("vcGender", gender_short);
jsonParams2.put("vcEmailAddress", email.getText().toString());
jsonParams2.put("vcPassword", password.getText().toString());
jsonParams2.put("vcFBID", "");
jsonParams2.put("intLoginUserID", "");
jsonParams2.put("SignUpFrom", "Web");
jsonParams2.put("intloginid", "");
jsonParams2.put("AlreadyRegister", "");
return jsonParams2;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put( "charset", "utf-8");
return headers;
}
};
The above code is heavily inspired by using answers from this community, but this does not seem to solve the problem for me.
I get Volley Error 405.
E/Volley﹕ [112549] BasicNetwork.performRequest: Unexpected response code 405 for http://myurl
Infact If I used AsyncTask instead of Volley, With the same json as parameters and the same endpoint url. It works!! The AsyncTask code was found from this question. Java HttpClient changing content-type?
But I want to use Volley, What could be the solution to this?
Sample JSON Object
{"vcFName":"Ron","vcLname":"Weasley","vcMobileNo":"555888999","vcGender":"M","vcEmailAddress":"someone#somewhere.com","vcPassword":"123456","vcFBID":"","intLoginUserID":'',"SignUpFrom":"Web","intloginid":"","AlreadyRegister":""}
You need to use JsonObjectRequest class. Pass your params as json object in the 3rd parameter of the JsonObjectRequest class. Below is a small snippet:
Map<String, String> jsonParams2 = new HashMap<String, String>();
jsonParams2.put("vcFName", firstname.getText().toString());
jsonParams2.put("vcLname", lastname.getText().toString());
jsonParams2.put("vcMobileNo", phone_no.getText().toString());
jsonParams2.put("vcGender", gender_short);
jsonParams2.put("vcEmailAddress", email.getText().toString());
jsonParams2.put("vcPassword", password.getText().toString());
jsonParams2.put("vcFBID", "");
jsonParams2.put("intLoginUserID", "");
jsonParams2.put("SignUpFrom", "Web");
jsonParams2.put("intloginid", "");
jsonParams2.put("AlreadyRegister", "");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
YourUrl, new JsonObject(jsonParams2),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put( "charset", "utf-8");
return headers;
}
};
Step 1: Make model class parsable/Serializable.
Step 2: Override toString() in model class.
Step 3:
Map<String,JSONObject> params = new HashMap<>();
JSONObject object = null;
try{
object = new JSONObject(classObject.toString());
}catch (Exception e){
}
params.put("key", object);
JSONObject objectParams = new JSONObject(params);
Step 4: Send objectParams with volley JSONObject request.
Done!!!
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.