How to send json data with header using volley library - android

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

Related

Volley GET with parameters

I have a web service which gives data in JSON array format. Right now the data is being fetched just by passing the URL. But now I want to pass a parameter to get the JSON response. This web service has GET & POST methods.
I tried with Volley - Sending a POST request using JSONArrayRequest answer, but I couldn't implement it in my code. It would be really helpful if somebody could explain, how to achieve this in my code.
This is how my code looks like
String HTTP_SERVER_URL = "https://192.168.1.7/STUDENTWS/Default.asmx/StudentDataJson?InFacultyID=string";
public void JSON_WEB_CALL(){
//mSwipeRefreshLayout.setRefreshing(true);
jsonArrayRequest = new JsonArrayRequest(HTTP_SERVER_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
DataModel GetDataModel = new DataModel();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataModel.setId(json.getString("STUDENTID"));
GetDataModel.setPlateNo(json.getString("GRADE"));
GetDataModel.setPlateCode(json.getString("HOUSE"));
}
catch (JSONException e)
{
e.printStackTrace();
}
DataAdapterClassList.add(GetDataModel);
mSwipeRefreshLayout.setRefreshing(false);
}
recyclerViewadapter = new NewRecyclerViewAdapter(DataAdapterClassList, this);
recyclerView.setAdapter(recyclerViewadapter);
if (array.length()!=0) {
SHOW_ALERT(array);
sendNotification(recyclerView, array);
}
}
For get with params you should create StringRequest. For example:
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.GET, "http://headers.jsontest.com/",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("HttpClient", "success! response: " + response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("HttpClient", "error: " + error.toString());
}
})
{
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("user","YOUR USERNAME");
params.put("pass","YOUR 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;
}
};
// for json object
Map<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("fullname",fullName);
jsonParams.put("email",email);
jsonParams.put("password",password);
// for json array make any list.List will be converted to jsonArray
// example-----
// ArrayList<String> jsonParams =new ArrayList();
// jsonParams.add("Test1")
// jsonParams.add("Test2")
JsonObjectRequest objectRequest=new JsonObjectRequest(Request.Method.POST, url, new JSONObject(jsonParams), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: ",error );
Toast.makeText(ActivitySignUp.this,error.getMessage(), Toast.LENGTH_LONG).show();
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String,String> header=new HashMap<String, String>();
header.put("Content-Type","application/json");
return header;
}
};
If you want to pass a param to your server, then you might wanna do a POST method, else.. if you only wanted to get the data, then GET method is the best way... there's also header that you can use to pass data, but, I wouldn't recommend to use header for sending params... that's a sore eyes
Edit
//Set you method POST or GET
JsonObjectRequest(Request.Method.GET(/*here can set to POST too*/), url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
// display response
Log.d("Response", response.toString());
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", response);
}
}
);

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 fails to send my Params to the server

I am trying send data to server using Volley library but it gives me an error
"end of input at character 0 of "
and here is my code
public void postPrams(View view) {
String tag_json_obj = "json_obj_req";
String url = "http://Urlhere.com/register.php";
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
text.setText("done Post : "+response);
pDialog.hide();
Toast.makeText(getApplication(),"Done",Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("erorr", "Error: " + error.getMessage());
Toast.makeText(getApplication(),error.getMessage().toString(),Toast.LENGTH_LONG).show();
pDialog.hide();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("first_name","Anwar");
params.put("last_name","Samir");
params.put("age", "1000");
params.put("country", "egypt");
params.put("city","le");
params.put("street", "10sq");
params.put("mobile_no", "0100000");
params.put("login_name", "Asi");
params.put("password", "123qwe");
return params;
}
};
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
Please help me why this is happening.
Have a look at Volley's source
public JsonObjectRequest(int method, String url, JSONObject jsonRequest,Listener<JSONObject> listener, ErrorListener errorListener)
You're passing null in the place of jsonRequest meaning that in fact you are not passing any data with the POST request. Hence the error: "end of input at character 0 of. Try changing your code to
public void postPrams(View view) {
String tag_json_obj = "json_obj_req";
String url = "http://Urlhere.com/register.php";
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, getParams(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
text.setText("done Post : "+response);
pDialog.hide();
Toast.makeText(getApplication(),"Done",Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("erorr", "Error: " + error.getMessage());
Toast.makeText(getApplication(),error.getMessage().toString(),Toast.LENGTH_LONG).show();
pDialog.hide();
}
});
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
private JSONObject getParams(){
JSONObject params = new JSONObject();
params.put("first_name","Anwar");
params.put("last_name","Samir");
params.put("age", "1000");
params.put("country", "egypt");
params.put("city","le");
params.put("street", "10sq");
params.put("mobile_no", "0100000");
params.put("login_name", "Asi");
params.put("password", "123qwe");
return params;
}
Look a the request method. Post or get?? Are you returning a vallue? or blank?.
In you server side try to do echo to parameters.
JSONObject params = new JSONObject();
params.put("first_name","Anwar");
params.put("last_name","Samir");
params.put("age", "1000");
params.put("country", "egypt");
params.put("city","le");
params.put("street", "10sq");
params.put("mobile_no", "0100000");
params.put("login_name", "Asi");
params.put("password", "123qwe");
replace null with params. You are not able to receive at server side since you are not sending any body.The Map in which you placed your params is for headers not the body.You have to send the body in
JsonObjectRequest request = newJsonObjectRequest(method,url,body,listener){
....headers here
};
try this
public void postDataVolley(Context context,String url,JSONObject sendObj){
try {
RequestQueue queue = Volley.newRequestQueue(context);
JsonObjectRequest jsonObj = new JsonObjectRequest(url,sendObj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Volley", "Volley JSON post" + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Volley", "Volley JSON post" + "That didn't work!");
}
});
queue.add(jsonObj);
}catch(Exception e){
}
}

Volley: unable to set break point for onResponse method

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!

how to send json object to server using volley in 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);
}

Categories

Resources