how to send json object to server using volley in android - android

I want to send the JSONObject to server using POST method . I have used volley library to pass the string params its working fine, but if i try to use json object its showing an error for calling the json object here is my code
private void makeJsonObjReq() {
showProgressDialog();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
Const.URL_LOGIN, null,
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;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("un", "xyz#gmail.com");
params.put("p", "somepasswordhere");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq,tag_json_obj);
// Cancelling request
// ApplicationController.getInstance().getRequestQueue().cancelAll(tag_json_obj);
}
And my Error form server is : [10031] BasicNetwork.performRequest: Unexpected response code 401
How to solve this problem. I want to add application/json;charset=utf-8 in header please check my code whether its correct or not . Please give me a suggestion to over come this problem

Third parameter in JsonObjectRequest is for passing post parameters in jsonobject form. And for header you need to send two separate values one for content-type one for charset.
RequestQueue queue = Volley.newRequestQueue(this);
private void makeJsonObjReq() {
showProgressDialog();
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;
}
};
jsonObjReq.setTag(TAG);
// Adding request to request queue
queue.add(jsonObjReq);
// Cancelling request
/* if (queue!= null) {
queue.cancelAll(TAG);
} */
}

Create new Method and call it in OnClick method
public void PostOperation() {
requestQueue = Volley.newRequestQueue(this);
pdialog = new ProgressDialog(this);
pdialog.setMessage("Loading");
pdialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, "YOUR_URL",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pdialog.dismiss();
Log.e("login output", response);
//MODEL CLASS
LoginModel loginModel = new GsonBuilder().create().fromJson(response, LoginModel.class);
if (loginModel.getStatus().toString().equalsIgnoreCase("true")) {
Intent i = new Intent(context, DashboardActivity.class);
startActivity(i);
finish();
Toast.makeText(context, loginModel.getStatus() + "", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, loginModel.getMsg() + "", Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pdialog.dismiss();
Toast.makeText(getApplicationContext(), "Invalid Credentials", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
HashMap<String, String> map = new HashMap<String, String>();
// pass your input text
map.put("email" editTextEmail.getText().toString());
map.put("password",editTextPassword.getText().toString() );
map.put("uid", "1");
map.put("type", "login");
Log.e("para", map + "");
return map;
}
};
requestQueue.add(stringRequest);
}

Related

How to send json data with header using volley library

I am trying to send json data to a url in the format below.
{
“amount”:500,
“merchant_id”:”104”,
“narrative”:”John”,
“reference”:”Steven”
}
To send data to the url, one needs an authorization key as the header, I have already figured out how to set the authorization key as the header in Params, as shown below
#Override
public Map<String,String >getHeaders()throws AuthFailureError{
Map<String,String >params=new HashMap<String,String>();
params.put(“Content-Type”, “text/jsom;);
params.put(“AuthKey”, Auth);
return params;
but I do not know how to send the data in the particular format shown in the first instance to the url using params with volley. Please help, I am quite new to using Volley library .
This is the rest of code I am currently using it however does not return any response except for an invalid json error. Meaning the format sent is not corresponding to the one desired.
StringRequest stringRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(Main9Activity.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Main9Activity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() {
HashMap<String, String> params = new HashMap<String, String>();
params.put("amount","500");
params.put("merchant_id", "104");
params.put("narrative","John");
params.put("reference", "Steven");
return params;
}
#Override public Map<String,String>getHeaders()throws AuthFailureError{
Map<String,String>headers=new HashMap<>();
params.put("Content-Type","text/json");
params.put("Authorization",Auth);
return params;
}
};
RequestQueue requestQueue=Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
You can refer below code snipet to post data with custom header in volley.
JSONObject jsonobject = new JSONObject();
jsonobject.put("amount", "500");
jsonobject.put("merchant_id", "104");
jsonobject.put("narrative", "John");
jsonobject.put("reference", "Steven");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.POST,url, jsonobject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
Toast.makeText(Main9Activity.this, response.toString(), Toast.LENGTH_SHORT).show();
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(Main9Activity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
hideProgressDialog();
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String >headers=new HashMap<String,String>();
headers.put(“Content-Type”, “application/json“);
headers.put(“AuthKey”, Auth);
return headers;
}
You can send as below:
The data you want to send:
Hashmap<String, Object> data = new HashMap<>();
data.put("amount", "500");
data.put("merchant_id", "104");
data.put("narrative", "John");
data.put("reference", "Steven");
RequestQueue request = Volley.newRequestQueue(context);
JsonObjectRequest jsonobj = new JsonObjectRequest(Request.Method.POST, "your url",new JSONObject(data),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
){
};
request.add(jsonobj);

BasicNetwork.performRequest - Unexpected response code 400 (POST)

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());
}
});

Android volley post methode parameter missing

I am using android volley library to post data to back-end service. But I can't send any parameter with my request. I have done each and everything mentioned here . But none works for me. The post method that I am using is:
public static void post()
{
// Tag used to cancel the request
String tag_json_obj = "json_obj_req";
String url = "http://myUrl";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "Error: " + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
return headers;
}
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("key", "value");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
Always the response is "parameter missing".
How could i resolve this issue?
If you're using JSONObjectRequest, you can try this.
String url = "http://myurl";
Map<String, String> params = new HashMap<String, String>();
params.put("key", value);
RequestQueue queue = Volley.newRequestQueue(getActivity());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
url, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
try {
success = jsonObject.getInt("success");
message = jsonObject.getString("message");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Activity activity = getActivity();
if (volleyError instanceof NoConnectionError) {
String errormsg = "Check your internet connection";
Toast.makeText(activity, errormsg, Toast.LENGTH_LONG).show();
}
}
});
queue.add(jsonObjectRequest);
The codes are more likely the same as yours. Check on the lines where I put the data to be posted. I'm very sure this would work!
The problem is you are approaching the request as though you were making a stringRequest. The link you reference is talking specifically about making a stringRequest.
jsonObjectRequest actually lets you put the json object into the constructor itself, instead of using the override method getParams() like so:
String url = "some_url";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put(Constants.LOGIN_EMAIL_ID, email);
jsonObject.put(Constants.LOGIN_PASSWORD, password);
}catch(JSONException e){
Log.d("JSON error", e.getMessage(), e);
}
JsonObjectRequest jsObjRequest = new JsonObjectRequest(url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("RESPONSE", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(error.getMessage()!=null){
Log.d("RESPONSE", error.getMessage());
}
}
});
VolleySingleton.getInstance(activity).getRequestQueue().add(jsObjRequest);

Android Volley: Put request not updating any data

i'm trying to update some data with android volley but not working. and with postman it works.
my code:
private void aceptarAlerta()
{
mRequestQueue = VolleySingleton.getInstance().getmRequestQueue();
SharedPreferences preferencia = getSharedPreferences("ComuniUsuario", Context.MODE_PRIVATE);
token = preferencia.getString("ComuniToken", null);
StringRequest stringRequest = new StringRequest(Request.Method.PUT, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Respuesta: ", response);
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("estado", "true");
params.put("cuidador", Tmensaje[2]);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "Token " + token);
return headers;
}
#Override
public RetryPolicy getRetryPolicy() {
return new DefaultRetryPolicy(
15000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
}
};
mRequestQueue.add(stringRequest);
}
and if i delete params from code i dont get any error response from server.
i don't know what's the problem, i think have a logical error.

Android Volley: null value being received at server for String params sent with POST request

I am sending POST query along with String data from android device using Volley library.
The server however, is receiving only null values for the params. My code goes like this:
final String param1 = "one";
final String param2 = "124843";
final String param3 = "878942";
final String param4 = "885942";
String url = getIPAddr()+":"+getPort()+"/com.va.jersey.helloworld/hello";
RequestQueue queue = Volley.newRequestQueue(getBaseContext());
StringRequest stringRequest = new StringRequest(Request.Method.POST,url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showOutput(response);
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
showOutput(error.toString());
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("param1", param1);
params.put("param2", param2);
params.put("param3", param3);
params.put("param3", param4);
return params;
} //attaching POST params
};
queue.add(stringRequest);
I believe there is some error in StringRequest, please correct...
Use the code given below and let me know if you are facing any issue
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
}) {
/**
* 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");
headers.put("apiKey", "xxxxxxxxxxxxxxx");
return headers;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

Categories

Resources