i am struggling to make this work, basically i get an id from previous activity using intent, now i want to send this id to server so it returns all the data associated with this id.
javacode
final String URL = "URL";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("ID", "1");
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));
print response in textview;
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);
PHP server
if (!empty($_POST)) {
$query = " SELECT * FROM table WHERE ID = :ID " ;
$query_params = array(
':ID' => $_POST['ID'],);
try {
$statement = $db->prepare($query);
$result = $statement->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database query error";
die(json_encode($response));
}
$result = $statement->fetchAll();
if($result){
$data =array();
foreach($result as $rows){
$json = array();
$json["Name"] = $rows["Name"];
array_push ($data,$json);
}
echo stripcslashes(json_encode($data, JSON_PRETTY_PRINT));
i used this example of http://www.itsalif.info/content/android-volley-tutorial-http-get-post-put and coverted the string response to string array, worked for me
url = "http://httpbin.org/post";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", response);
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("name", "Alif");
params.put("domain", "http://itsalif.info");
return params;
}
};
queue.add(postRequest);
I would modify the request like this:
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,URL,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
print response in textview;
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("ID", "1");
return params;
}
};
ApplicationController.getInstance().addToRequestQueue(req);
and also would modify the PHP code like this:
if (isset($_POST['ID'])) {
$id = $_POST['ID'];
try {
$statement = $db->prepare(SELECT * FROM table WHERE ID = ?);
$statement->bindValue(1, $id);
$result = $statement->execute();
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database query error";
die(json_encode($response));
}
$records = array();
$records = $statement->fetchAll(PDO::FETCH_ASSOC);
$data = array();
foreach($records as $record){
$data["Name"] = $record["Name"];
}
echo stripcslashes(json_encode($data, JSON_PRETTY_PRINT));
}
Hope it helps!!!
the issue is that you send json but you expect params in you php.
there 2 solutions:
1) update php to accept json not just post params
2) update volley request to send post params but expect JSONObject
for example you can use this request:
public class JsonObjReq extends Request<JSONObject> {
private final Response.Listener<JSONObject> mListener;
private final Map<String, String> params;
public JsonObjReq(int method, String url, Map<String, String> params, Response
.Listener<JSONObject> mListener,
Response.ErrorListener listener) {
super(method, url, listener);
this.mListener = mListener;
this.params = params;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return params;
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, "utf-8"));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONObject response) {
mListener.onResponse(response);
}
}
and apply to your code like that:
final String URL = "URL";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("ID", "1");
JsonObjReq req = new JsonObjReq(Method.POST, URL, params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
print response in textview;
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);
Related
I am trying to send a JSON object request with two parameters and in response trying to get an array from the api call. However, I am getting exception parse error in Error listener. A post request is sent when the button is clicked. The func takes two parameters but fails to get response, the function directly goes to on response error listener
private void validate_log(String num) {
/*buttonNumCheck.setVisibility(View.INVISIBLE);
final ProgressBar pBar=(ProgressBar)findViewById(R.id.progressBarLogin);
pBar.setVisibility(View.VISIBLE);*/
buttonNumCheck.setInProgress(true);
buttonNumCheck.setEnabled(false);
final String Org_id="81";
final String url="http://xya/api";
RequestQueue rq=Volley.newRequestQueue(this);
JSONObject js=new JSONObject();
try {
js.put("parm1", num);
js.put("parm2", Org_id);
final String requestBody=js.toString();
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjReq=new JsonObjectRequest(
Request.Method.POST, url, js,
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
buttonNumCheck.setEnabled(true);
buttonNumCheck.setInProgress(false);
String stresponse=response.toString();
Toast.makeText(getApplicationContext(),"REPOSE="+response,Toast.LENGTH_SHORT).show();
System.out.println("RESPONSE= "+response);
try {
JSONArray heroArray = response.getJSONArray("");
// Toast.makeText(DeviceCheck_Activity.this, "Welcome Back"+ [1], Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
Log.e("Error", "Response Error", e);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(DeviceCheck_Activity.this, "Response error= " + error, Toast.LENGTH_LONG).show();
/*mdToast=MDToast.makeText(getApplicationContext(), "Oops something went wrong!!",
Toast.LENGTH_SHORT, MDToast.TYPE_ERROR);
mdToast.show();*/
buttonNumCheck.setInProgress(false);
buttonNumCheck.setEnabled(true);
Log.e("Error", "Response Error", error);
}
}) {
#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.setShouldCache(false);
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rq.add(jsonObjReq);
}
The error response I am getting is
com.android.volley.ParseError: org.json.JSONException: Value [{"store_id":11,"store_name":"Gomati District Main Store"},{"store_id":13,"store_name":"Main Seed Store"}] of type org.json.JSONArray cannot be converted to JSONObject
Your Problem can be solved in 2 ways :
First:)
Using JSONArrayRequest instead of JSONbjectRequest.
Your JSONObjectRequest returns an JSONObject response while your response is an JSONArray therefore java can not convert it and your application crashes.
Change you request as below:
JSONArrayRequest jsonArrReq=new JSONArrayRequest(//changed
Request.Method.POST, url, js,
new Response.Listener<JSONArray>() {
public void onResponse(JSONArray response) {
JSONArray heroArray = response;//changeed
/* rest of your code */
} catch (JSONException e) {
e.printStackTrace();
Log.e("Error", "Response Error", e);
}
}
},
jsonArrReq.setShouldCache(false);
jsonArrReq.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rq.add(jsonArrReq);
Second :)
Using StringRequest instead of JSONObjectRequest. String request returns an String response which lets you do what ever you want with your response.
Change you request as below :
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONArray heroArray = new JSONArray(response);
/* rest of your code */
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", "Response Error", error);
/*rest of your code */
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : js.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", js, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
}
stringRequest.setShouldCache(false);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rq.add(stringRequest);
Use the JsonArrayRequest like thisas your response is JsonArray .
JsonArrayRequest jsonObjReq = new JsonArrayRequest(Request.Method.POST, url, js,
new Response.Listener<JSONArray>() {
public void onResponse(JSONArray response) {
buttonNumCheck.setEnabled(true);
buttonNumCheck.setInProgress(false);
String stresponse = response.toString();
try {
for (int i = 0; i < response.length(); i++) {
JSONObject object = response.getJSONObject(i);
String id = object.getString("store_id");
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("Error", "Response Error", e);
}
}
}
Tried all the solutions didn't worked but thank you guys for your help. I actually found the solution from another question posted in stack overflow page. Here is the solution:
RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//JSONArray jsonArray_1=new JSONArray(response);
System.out.println("RESPONSE= " + response);
JSONArray jsonArray=new JSONArray(response);
json_stringarr=new String[jsonArray.length()];
if(jsonArray.length()>0) {
for (int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
//String web_page=jsonObject1.getString("awb_no");
String store_id=jsonObject1.getString("store_id");
String store_name=jsonObject1.getString("store_name");
json_stringarr[i]=store_id+" - "+store_name;
Toast.makeText(getApplicationContext(), "RESPOBBSE= " + json_stringarr[i], Toast.LENGTH_SHORT).show();
System.out.println("JSON ARRAY=" + json_stringarr[i]);
System.out.println("JSON Object=" + jsonObject1);
}
}
else{
Toast.makeText(getApplicationContext(),"Login ceredentils are incorrect",Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
MDToast mdToast=MDToast.makeText(getApplicationContext(), "Something went wrong!!", Toast.LENGTH_SHORT, MDToast.TYPE_WARNING);
mdToast.show();
error.printStackTrace();
}
}) {
#Override
public byte[] getBody() {
// String body="{\"param1\":"+num+",\"param2\":\"81"\"}";
String body="{\"parm1\":"+num+",\"parm2\":\"81\"}";
return body.getBytes();
}
/*#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("param1", num);
params.put("param2", Org_id);
return params;
}*/
#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;
}
};
I did it by sending a String request and then overriding the getBody() method and then it worked like a charm. Thanks again for all your help.
Hi I am using volley as JSON Parsing. I am using POST method and sending parameters in post request. I am getting following error when parsing the data, I am getting following error. I want to use volley. I have tried with JsonArrayRequest but it does not allow to send parameters as JSONObject,which I am using in my code.
org.json.JSONArray cannot be converted to JSONObject
Request is like
{
"city":"acd",
"user_id":"82",
"phone_number1":"1232131231",
"my_type":"asf"
}
Response is like
[{
"name":"dfdfd",
}]
Following is my code
private void Search_Refer() {
//initialize the progress dialog and show it
progressDialog = new ProgressDialog(SearchReferNameActivity.this);
progressDialog.setMessage("Please wait....");
progressDialog.show();
try {
JSONObject jsonBody = new JSONObject();
jsonBody.put("city", "acb");
jsonBody.put("user_id", "82");
jsonBody.put("phone_number1", "12332123231");
jsonBody.put("my_type", "asf");
JsonObjectRequest jsonOblect = new JsonObjectRequest(Request.Method.POST, Constants.BASE_URL1+"api/lab/search", jsonBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
Log.e("Search EROOR", response.toString());
try {
JSONArray itemArray=new JSONArray(response);
dataModelArrayList = new ArrayList<>();
for (int i = 0; i < itemArray.length(); i++) {
SearchModel playerModel = new SearchModel();
JSONObject dataobj = itemArray.getJSONObject(i);
//playerModel.setProduct_name(dataobj.getString("name"));
playerModel.setRadiology_store_first_name(dataobj.getString("radiology_store_first_name"));
dataModelArrayList.add(playerModel);
}
} catch (JSONException e) {
e.printStackTrace();
}
progressDialog.dismiss();
/* Intent intent = new Intent(SearchReferNameActivity.this, SearchResult.class);
intent.putExtra("Search_result", dataModelArrayList);
startActivity(intent);*/
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Response: " + error.toString(), Toast.LENGTH_SHORT).show();
System.out.println("Search Eroor"+error.toString());
progressDialog.dismiss();
}
}){
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "Bearer "+deviceToken);
return headers;
}
};
jsonOblect.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MyApplication.getInstance().addToRequestQueue(jsonOblect,"postrequest");
} catch (JSONException e) {
e.printStackTrace();
}
// Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_LONG).show();
}
Use JsonArrayRequest or StringRequest in place of JsonObjectRequest
JsonArrayRequest
change the following response parameter to JSONArray
Instead of new Response.Listener<JSONObject> Use new Response.Listener<JSONArray>
// JSONArray insated of JSONObject
public void onResponse(JSONArray response) {
}
Use Below code
StringRequest stringRequest = new StringRequest(Request.Method.POST, "api/lab/search", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("city", "abcd");
params.put("user_id", "82");
params.put("phone_number1", "01235467895");
params.put("my_type", "asf");
return params;
}
};
I am making a new android application and i am a beginner. starting with my Login Activity, i am trying to use POST for sending parameters. but when i debug i found no parameters being passed. Tried almost many answers in stack overflow, none solved my issue. Can anyone help
private void jsonRequestLogin() {
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = Constants.LOGIN_URL;
JSONObject jsonBody = new JSONObject();
jsonBody.put("Username", uName.getText().toString().trim());
jsonBody.put("Password", paswd.getText().toString().trim());
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
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;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
Use getParams() method for requesting the parameters
private void check() {
StringRequest stringRequest = new StringRequest(Request.Method.POST,url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Log.d(TAG, "onResponse:" + response);
try {
JSONArray responseArray = new JSONArray(response);
JSONObject jsonObject = responseArray.getJSONObject(0);
//Log.d(TAG, "onResponse: jsonArray " + responseArray);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Log.d(TAG, "onErrorResponse: " + error);
Toast.makeText(SplashScreenActivity.this, "Some error occurred try after sometimes", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("param1",param1);
params.put("param2", param2;
//Log.d(TAG, "getParams: " + params);
return params;
}
};
addToRequestQueue(stringRequest, "");
}
Try to override the headers method and put content type init.
#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;
}
I think you should use retrofit
Retrofit
Retrofit 2
Android Code:
private void registerUser(){
final String username = "subrata";
final String password = "banerjee";
final String email = "test_email";
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_USERNAME,username);
params.put(KEY_PASSWORD,password);
params.put(KEY_EMAIL, email);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
I'm trying to send http request using Android Volley to my node.js server (expressjs). Its hitting the server and getting the response but when I'm printing the req.body in node.js its shows {} (empty). I'm new to Android and unable to figure out the reason. Please someone guide me.
Call this method in OnResponse GetResponse(response);
And the method will be
private void GetResponse(String res){
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(res);
JSONArray result = jsonObject.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
JSONObject jo = result.getJSONObject(i);
String temp = jo.getString("what_ever");
String temp1 = jo.getString("what_ever_1");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
This will get you the response in String format fetched from json.
private void registerUser(){
JSONObject jsonBodyObj = new JSONObject();
try{
jsonBodyObj.put("mAtt", "+1");
jsonBodyObj.put("mDatum","+2");
jsonBodyObj.put("mRID","+3");
jsonBodyObj.put("mVon","+4");
}catch (JSONException e){
e.printStackTrace();
}
final String requestBody = jsonBodyObj.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG).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");
headers.put("User-agent", "My useragent");
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;
}
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
I have to send a post with voley but when i try to send raw body as requested, instead of a response a get this error
******com.android.volley.ServerError******: {"message":"No user account data for registration received."}
i tried the same in postman and it works perfect, how can i fix it in my code?
raw body that works in postman ->
{
"camp1": {
"value": "value"
},
"camp2": {
"value": "value2"
}
}
this is what it is in my code ->
public void requestRegistrationInfo(#NonNull final String camp1, #NonNull final String camp2,final Listener listener) {
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(new JsonObjectRequest(
Request.Method.POST, URL,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.v("IT WORK");
listener.onSuccess();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("******" + error.toString() + "******", getErrorMessage(error));
listener.onFailure();
}
})
{
#Override
protected Map<String,String> getParams() {
Map<String, String> map = new HashMap<>();
map.put("{camp1", "value");
map.put("camp2", "value");
return map;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put("header1", "header1");
map.put("header2", "header2");
return map;
}
});
}
what can i do to send raw json correctly and don't show the error?
In normal case JSONObject request didn't hit the getParams() method , this method only for String request and passing key value pair data payload. If you want to pass a raw body with JSON data , first you have to format your data as server accepted.
In your case this is your data
{
"camp1":{
"value":"value1"
},
"camp2":{
"value2":"value2"
}
}
You have to convert your data to Server accepted JSON format like this
JSONObject jsonObject = new JSONObject();
jsonObject.put("value", "value1");
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("value2", "value2");
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("camp1", jsonObject);
jsonObject2.put("camp2",jsonObject1);
//jsonObject2 is the payload to server here you can use JsonObjectRequest
String url="your custom url";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.POST,url, jsonObject2, new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
//TODO: Handle your response here
}
catch (Exception e){
e.printStackTrace();
}
System.out.print(response);
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
error.printStackTrace();
}
});
JsonObjectRequest will accept the payload as json in its constructor after the url parameter we will pass the data
This is tested Code try this:
private void multipartRequestWithVolly() {
String urll = "your_url";
progressDialog.show();
StringRequest request = new StringRequest(Request.Method.POST, urll, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
if (!TextUtils.isEmpty(response)) {
Log.e(TAG, "onResponse: " + response);
textView.setText(response);
} else {
Log.e(TAG, "Response is null");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Log.e(TAG, "onErrorResponse: " + error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
hashMap = new HashMap<>();
hashMap.put("OPERATIONNAME", "bplan");
hashMap.put("mcode", "298225816992");
hashMap.put("deviceid", "dfb462ac78317846");
hashMap.put("loginip", "192.168.1.101");
hashMap.put("operatorid", "AT");
hashMap.put("circleid", "19");
return hashMap;
}
};
AppController.getInstance().addToRequestQueue(request);
}
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://...";
JSONObject jsonBody = new JSONObject();
jsonBody.put("Title", "Android Volley Demo");
jsonBody.put("Author", "BNK");
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : encodeParameters(requestBody , getParamsEncoding());
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
Please check with the edited getBody()
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : encodeParameters(requestBody , getParamsEncoding());
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
If you calling any REST-API then note that that's payload always be in JSON format. therefor you can use an object body for payload like this way.
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", input_loginId.getText().toString());
params.put("password", input_password.getText().toString());
and you can pass this on method like this way
JsonObjectRequest logInAPIRequest = new JsonObjectRequest(Request.Method.POST, YOUR-URL,
new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
input_errorText.setText(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
input_errorText.setText("Error: " + error.getMessage());
}
});