Android Volley post json data to server
public void postData(String url,Hashmap data,final VolleyCallback mResultCallback){
RequestQueue requstQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonobj = new JsonObjectRequest(Request.Method.POST, url,new JSONObject(data),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if(mResultCallback != null){
mResultCallback.notifySuccess(response);
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null){
mResultCallback.notifyError(error);
}
}
}
){
//here I want to post data to sever
};
requstQueue.add(jsonobj);
}
Now, from your mainActiviy class
Hashmap data = new HashMap();
data.put("email","email");
data.put("password","password");
String url = "http://example.com";
//now you can just call the method, I have rectified your string to hashmap,
postData(url,data,new mResultCallb..... //rest of your code
Send POST request with JSON data using Volley
JsonObjectRequest
actually accepts JSONObject
as body.
From this blog article,
final String url = "some/url";
final JSONObject jsonBody = new JSONObject("{\"type\":\"example\"}");
new JsonObjectRequest(url, jsonBody, new Response.Listener<JSONObject>() { ... });
Here is the source code and JavaDoc (@param jsonRequest
):
/**
* Creates a new request.
* @param method the HTTP method to use
* @param url URL to fetch the JSON from
* @param jsonRequest A {@link JSONObject} to post with the request. Null is allowed and
* indicates no parameters will be posted along with request.
* @param listener Listener to receive the JSON response
* @param errorListener Error listener, or null to ignore errors.
*/
public JsonObjectRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONObject> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
errorListener);
}
Android Volley POST Json to Server
- Make a volley request like bellow which takes method like
POST/GET
,url
,response & error
listener. And For sending your json overridegetBody()
method in which pass the json you want to send. - Make a
RequestQueue
& add the request to it. You might start it by
callingstart()
Try this :
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// your response
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// error
}
}){
@Override
public byte[] getBody() throws AuthFailureError {
String your_string_json = ; // put your json
return your_string_json.getBytes();
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
requestQueue.start();
For more info see this
How to send json data with header using volley library
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;
}
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 post JSON data using volley library?
IMO, you can refer to my following sample code:
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://...";
// Prepares POST data...
JSONObject jsonBody = new JSONObject();
jsonBody.put("TakeoffID", "2");
jsonBody.put("ViewPhoto1", "image base64 content");
jsonBody.put("ViewPhoto2", "image base64 content");
// "OrderLineid": "964"...
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("OrderLineid","964");
jsonObject1.put("OrderLinePhoto1","image base64 content");
jsonObject1.put("OrderLinePhoto2","image base64 content");
// "OrderLineid": "963"...
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("OrderLineid","963");
jsonObject2.put("OrderLinePhoto1","image base64 content");
jsonObject2.put("OrderLinePhoto2","image base64 content");
JSONArray jsonArray = new JSONArray();
jsonArray.put(jsonObject1);
jsonArray.put(jsonObject2);
// "LineItems"...
jsonBody.put("LineItems", jsonArray);
final String mRequestBody = jsonBody.toString();
// Volley request...
StringRequest request = 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 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;
}
}
};
requestQueue.add(request);
} catch (JSONException e) {
e.printStackTrace();
}
Hope it helps!
How to send JSONObject to server as form-data using Volley
Here is the answer: https://stackoverflow.com/a/39718240/3024933
You need to override the getParams()
method and use StringRequest
instead of JsonObjectRequest
.
How to send json array as post request in volley?
If you are having a problem in calling the API then this will help you.
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jobReq = new JsonObjectRequest(Request.Method.POST, url, jObject,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
}
});
queue.add(jobReq);
where jObject is the JSON data you want to send to the server.
Implementation will be similar for JSONArray. Instead of JsonObjectRequest
use JsonArrayRequest and send jArray instead of jObject.
For creating json array just do a little tweak
JSONArray array=new JSONArray();
for(int i=0;i<filter_items.size();i++){
JSONObject obj=new JSONObject();
try {
obj.put("filterId",filter_items.get(i));
obj.put("typeName","CAT_ID");
} catch (JSONException e) {
e.printStackTrace();
}
array.put(obj);
}
And finally add json array as below
jsonParams.put("filter",array);
In your case you are converting Json array to string
Related Topics
How to Connect Localhost in the Android Emulator
Scrollview Not Scrolling in Android Bottomsheet
Making Voice Calls from Android Phone Connected to Linux
How to Emulate Gps Location in the Android Emulator
How to Show the Number Keyboard on an Edittext in Android
How to Clear Navigation Stack After Navigating to Another Fragment in Android
Background Drawable Not Applying to Button
Dynamically Setting Visibility of Textview in Recyclerview
Change Button Background At Runtime in Android
Storage Permission Error in Marshmallow
Suppress Keyboard from Popping Up
Could Not Resolve All Dependencies for Configuration ':Classpath'
How to Dismiss Notification After Action Has Been Clicked
Android Textview Text Not Getting Wrapped
How to Dynamically Hide a Menu Item in Bottomnavigationview
Super.Onbackpressed() and Finish() Exits the App
Retrieve Stored Image from Firebase Storage
Android: How to Enable/Disable Option Menu Item on Button Click