How to Send JSON Object to Server Using Volley in Android

how to send json object to server using volley in android

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);
} */

}

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

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

Volley send JSONObject to server with POST method

You can use the following working sample code. I have tested. Hope this helps!

       try {
jsonBody = new JSONObject();
jsonBody.put("Title", "VolleyApp Android Demo");
jsonBody.put("Author", "BNK");
jsonBody.put("Date", "2015/08/26");
requestBody = jsonBody.toString();

StringRequest stringRequest = new StringRequest(1, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
textView.setText(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
textView.setText(error.toString());
}
}) {
@Override
public String getBodyContentType() {
return String.format("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;
}
}
};
MySingleton.getInstance(this).addToRequestQueue(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}

UPDATE: To create JSONObject as your requirement, use the following:

        JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("11", 3);
jsonObject.put("12", 4);
jsonObject.put("13", 5);

JSONObject jsonObject2 = new JSONObject().put("answers", jsonObject);
jsonObject2.put("user_id", 12);
} catch (JSONException e) {
e.printStackTrace();
}

Android Volley POST Json to Server

  1. Make a volley request like bellow which takes method like POST/GET,
    url, response & error listener. And For sending your json override
    getBody() method in which pass the json you want to send.
  2. Make a RequestQueue & add the request to it. You might start it by
    calling start()

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

Volley Post request ,Send Json object in Json array request

Seems like it was removed in recent volley version but you can easily modify this constructor and add to JsonArrayRequest.

public JsonArrayRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONArray> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
errorListener);
}


Related Topics



Leave a reply



Submit