How to send a POST request using volley with string body?
You can refer to the following code (of course you can customize to get more details of the network response):
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 : 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();
}
POST request with Volley with headers and body (java, android studio)
You are correctly setting the headers, you could try this
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "https://url.of.the.server";
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 {
// request body goes here
JSONObject jsonBody = new JSONObject();
jsonBody.put("attribute1", "value1");
String requestBody = jsonBody.toString();
return 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
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
params.put("id", "oneapp.app.com");
params.put("key", "fgs7902nskagdjs");
return params;
}
@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));
}
};
Log.d("string", stringRequest.toString());
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
For example, if request body is
{
name: "name1",
email: "email1"
}
getBody
method would be
@Override
public byte[] getBody() throws AuthFailureError {
JSONObject jsonBody = new JSONObject();
jsonBody.put("name", "name1");
jsonBody.put("email", "email1");
String requestBody = jsonBody.toString();
return requestBody.getBytes("utf-8");
}
How to use POST request in android Volley library with params and header?
**Try this one **
private void sendWorkPostRequest() {
try {
String URL = "";
JSONObject jsonBody = new JSONObject();
jsonBody.put("email", "abc@abc.com");
jsonBody.put("password", "");
jsonBody.put("user_type", "");
jsonBody.put("company_id", "");
jsonBody.put("status", "");
JsonObjectRequest jsonOblect = new JsonObjectRequest(Request.Method.POST, URL, jsonBody, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), "Response: " + response.toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
onBackPressed();
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
final Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Basic " + "c2FnYXJAa2FydHBheS5jb206cnMwM2UxQUp5RnQzNkQ5NDBxbjNmUDgzNVE3STAyNzI=");//put your token here
return headers;
}
};
VolleyApplication.getInstance().addToRequestQueue(jsonOblect);
} catch (JSONException e) {
e.printStackTrace();
}
// Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_LONG).show();
}
}
How to send a POST request with JSON body using Volley?
Usual way is to use a HashMap
with Key-value pair as request parameters with Volley
Similar to the below example, you need to customize for your specific requirement.
Option 1:
final String URL = "URL";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "token_value");
params.put("login_id", "login_id_value");
params.put("UN", "username");
params.put("PW", "password");
JsonObjectRequest request_json = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
//Process os success response
} 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(request_json);
NOTE: A HashMap can have custom objects as value
Option 2:
Directly using JSON in request body
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://...";
JSONObject jsonBody = new JSONObject();
jsonBody.put("firstkey", "firstvalue");
jsonBody.put("secondkey", "secondobject");
final String mRequestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.i("LOG_VOLLEY", response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG_VOLLEY", error.toString());
}
}) {
@Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
@Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
return null;
}
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
How to Pass Array in Body of POST Request Using Volley In Android
This is the solution
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.SAVE_ITEM,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(SelectedPurchaseActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SelectedPurchaseActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("purchase_no", "87676767");
params.put("supplier", "7");
params.put("date", "2020-12-02");
params.put("p_type", "Cash");
params.put("medicine_id[]","618");
params.put("code[]", "202012011");
params.put("expiry_date[]", "2021-01-09");
params.put("batch_no[]", "1");
params.put("qty[]", "1");
params.put("cost[]", "1234");
params.put("total[]", "2468");
params.put("totalQty", "2");
params.put("subTotal", "2468");
params.put("discount", "3");
params.put("d_type", "%");
params.put("payable", "2394");
params.put("paid", "3");
params.put("due", "2391");
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", token);
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(SelectedPurchaseActivity.this);
queue.add(stringRequest);
Android - How to use Volley HTTP Post with element tags in body
I found this to be much easier than expected... Just change the body as follows:
@Override
public byte[] getBody() throws AuthFailureError {
String data =
"<sci_request version=\"1.2\">" +
"<data_service>" +
"<targets>" +
"<device id=\"1234-5678\" />" +
"</targets>" +
"<requests>" +
"<device_request target_name=\"myTarget\">" +
"some request string value" +
"</device_request>" +
"</requests>" +
"</data_service>" +
"</sci_request>";
return data.getBytes();
}
It should be noted that this is a Volley StringRequest and not all code is shown here.
Related Topics
How to Add a Border to the Top and Bottom of an Android View
How to Check If Alarmmanager Already Has an Alarm Set
How to Use Disk Caching in Picasso
Android View.Getdrawingcache Returns Null, Only Null
Error Inflating Class Fragment
Outofmemoryerror: Bitmap Size Exceeds Vm Budget :- Android
How to Disable Landscape Mode in Android
How to Dynamically Update a Listview on Android
How to Resume Existing Fragment from Backstack
How to Save Recyclerview'S Scroll Position Using Recyclerview.State
Dialog With Transparent Background in Android
What Is Activity.Finish() Method Doing Exactly
Check If Application Is Installed - Android
Html.Fromhtml Deprecated in Android N