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!!!
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 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 am trying to fetch data through rest api using Volley StringRequest or JsonObjectRequest. I always get 400 error. Its working fine with the postman. Http request method is POST, Content-Type is application/x-www-form-urlencoded. I have also checked my parameter spelling and it looks fine to me. I have tried with both StringRequest and JsonObjectRequest, result is E/Volley: [10283] BasicNetwork.performRequest: Unexpected response code 400. Below is my code. I have attached a screenshot.
Here is the new screenshot
StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
viewHelper.hideDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.toString());
viewHelper.hideDialog();
}
}){
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", email);
params.put("password", password);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
#Override
public String getBodyContentType(){
return "application/x-www-form-urlencoded";
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(stringRequest, "Authenticating User");
I have alos tried with volley JSONObjectRequest
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", email);
params.put("password", password);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, AppConfig.URL_LOGIN, new JSONObject(params), 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/x-www-form-urlencoded");
return headers;
}
};
Can anyone please help me in fixing this issue.
Below is the working example of POST request using Volley library.
Add this to your build.gradle (Module:app) -
compile 'com.mcxiaoke.volley:library:1.0.19'
StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
progressDialog.dismiss();
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
if(jsonObject.has("success")){
if(jsonObject.getBoolean("success") == true){
JSONObject userObject = new JSONObject(jsonObject.getString("user"));
Map<String, String> loginDetails = new HashMap<String, String>();
loginDetails.put(KEY_IS_LOGGED_IN, "true");
loginDetails.put(ACCESS_TOKEN, jsonObject.getString(ACCESS_TOKEN));
loginDetails.put(USERID, userObject.getString(USERID));
loginDetails.put(FIRSTNAME, userObject.getString(FIRSTNAME));
loginDetails.put(LASTNAME, userObject.getString(LASTNAME));
loginDetails.put(EMAIL, userObject.getString(EMAIL));
session = new SessionManager(_myActivity);
session.setLogin(loginDetails);
Intent intent = new Intent(LoginActivity.this, SearchActivity.class);
intent.putExtra("FROM_ACTIVITY", "LoginActivity");
startActivity(intent);
LoginActivity.this.finish();
}else{
btnLogin.setClickable(true);
btnLogin.setEnabled(true);
Toast.makeText(getApplicationContext(), "Username or Password does not matched!", Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
btnLogin.setClickable(true);
btnLogin.setEnabled(true);
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Something went wrong, Please try agian", Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.toString());
progressDialog.dismiss();
btnLogin.setClickable(true);
btnLogin.setEnabled(true);
}
}){
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", email);
params.put("password", password);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
#Override
public String getBodyContentType(){
return "application/x-www-form-urlencoded";
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
RequestQueue mRequestQueue = Volley.newRequestQueue(getApplicationContext());
mRequestQueue.add(stringRequest);
Please comment if anyone faced issue with above code.
Thanks to everyone who tried to help me.
A 400 means bad request the data sent by the you to the server didn't follow the rules.So check your parameter or spelling of these parameter which is required by server.
So check those try again hope it work for you :)
Unexpected response code 400 means Bad Reuest.
This Response is caused by sending wrong parameters with the URL.
To solve:
Check every parameter with spelling.
Make sure if response is obtained in string or in object. stringRequest or JSONObjectReuest
Also check Content-type
use this as Content-type
#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;
}
For JsonObjectReuest use:
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", "BLah");
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d("Response:", response.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error: ", error.getMessage());
}
});
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 can POST Map <String, String> to my server but it comes in & separated form.
I have used code from Send post request using Volley and receive in PHP
getParams() just doesn't work with JSONObject return type. Is it possible to send JSONObject as JSON only?
I want to send data as JSON that I will get using file_get_contents(php://input).
For this I have changed Content-Type to application/json; charset=utf-8.
The problem is using this way I get data in format of x=abc&y=def as it's Map<String, String> type and I want data in JSON format of {"x":"abc", "y":"def"}
It's different from above question because I want to POST data in JSON ONLY and not in MAP of String
Try this :
private void jsonObjReq() {
showProcessDialog();
Map<String, String> postParam= new HashMap<String, String>();
postParam.put("un", "xyz#gmail.com");
postParam.put("p", "somepasswordhere");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
Const.URL_LOGIN, new JsonObject(postParam),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
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;
}
};
change header in your php too.
the easy way is this
final RequestQueue requestQueue = Volley.newRequestQueue(this);
final String url ="http://mykulwstc000006.kul/Services/Customer/Register";
Map<String, String> params = new HashMap<String, String>();
params.put("MobileNumber", "+97333765439");
params.put("EmailAddress", "danish.hussain4#das.com");
params.put("FirstName", "Danish2");
params.put("LastName", "Hussain2");
params.put("Country", "BH");
params.put("Language", "EN");
JsonObjectRequest req = new JsonObjectRequest(url, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
}){
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
String username ="eli#gmail.com";
String password = "elie73";
String auth =new String(username + ":" + password);
byte[] data = auth.getBytes();
String base64 = Base64.encodeToString(data, Base64.NO_WRAP);
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization","Basic "+base64);
return headers;
}
};
requestQueue.add(req);
}