Volley - Sending a Post Request Using JSONarrayrequest

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

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

Sending a POST request with JSONArray using Volley

You can refer to my following sample code:

UPDATE for your pastebin link:

Because the server responses a JSONArray, I use JsonArrayRequest instead of JsonObjectRequest. And no need to override getBody anymore.

        mTextView = (TextView) findViewById(R.id.textView);
String url = "https://api.orange.com/datavenue/v1/datasources/2595aa553d3049f0b0f03fbaeaa7ddc7/streams/9fe5edb1c76e4968bdcc9c902010bc6c/values";
RequestQueue requestQueue = Volley.newRequestQueue(this);
final String jsonString = "[\n" +
" {\n" +
" \"value\": 1\n" +
" }\n" +
"]";
try {
JSONArray jsonArray = new JSONArray(jsonString);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, url, jsonArray, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
mTextView.setText(response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mTextView.setText(error.toString());
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("X-OAPI-Key","TQEEGSk8OgWlhteL8S8siKao2q6LIGdq");
headers.put("X-ISS-Key","2b2dd0d9dbb54ef79b7ee978532bc823");
return headers;
}
};
requestQueue.add(jsonArrayRequest);
} catch (JSONException e) {
e.printStackTrace();
}

My code works for both Google's official volley libray and mcxiaoke's library

If you want to use Google's library, after you git clone as Google documentation, copy android folder from \src\main\java\com (of Volley project that you cloned) to \app\src\main\java\com of your project as the following screenshot:

Sample Image

The build.gradle should contain the following

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.google.code.gson:gson:2.3.1'
}

If your project uses mcxiaoke's library, the build.gradle will look like the following (pay attention to dependencies):

apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.0"

defaultConfig {
applicationId "com.example.samplevolley"
minSdkVersion 16
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.0.0'
compile 'com.mcxiaoke.volley:library:1.0.17'
compile 'com.google.code.gson:gson:2.3'
}

I suggest that you will create 2 new sample projects, then one will use Google's library, the other will use mcxiaoke's library.

END OF UPDATE

        String url = "http://...";
RequestQueue requestQueue = Volley.newRequestQueue(this);
final String jsonString = "[\n" +
" {\n" +
" \"value\": 1\n" +
" }\n" +
"]";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// do something...
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// do something...
}
}) {
@Override
public byte[] getBody() {
try {
return jsonString.getBytes(PROTOCOL_CHARSET);
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
jsonString, PROTOCOL_CHARSET);
return null;
}
}
};
requestQueue.add(jsonObjectRequest);

The following screenshot is what server-side web service received:

Sample Image

How to post request parameters when using JsonArrayRequest in Volley

This solved my problem to pass params when JsonArrayRequest and POST method is used.

Volley.newRequestQueue(getActivity())
.add(new JsonRequest<JSONArray>(Request.Method.POST,
MySingleton.getInstance().getDOWNLOAD_SERVICES_URL(),
jsonobj.toString(),
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray jsonArray) {
Log.d("response", "res-rec is" + jsonArray);
if (jsonArray == null) {
pDialog.dismiss();
Snackbar.make(myview, "No services found", Snackbar.LENGTH_LONG).show();

} else {

for (int i = 0; i < jsonArray.length(); i++) {
try {

pDialog.dismiss();
JSONObject jsonObject = jsonArray.getJSONObject(i);
String desc = jsonObject.getString("SvcTypeDsc");
String image_url = jsonObject.getString("ThumbnailUrl");
// al_ImageUrls.add(image_url);

al_list_of_services.add(desc);
ad_servicesadapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, al_list_of_services);

lv_webservicesList.setAdapter(ad_servicesadapter);

Log.d("imageurls", "imagesurl " + image_url);
Log.d("services-list", "list is " + desc + " " + i);
} catch (JSONException e) {
e.printStackTrace();
}

}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
VolleyLog.d("Login request", "Error: " + volleyError.getMessage());
Log.d("Volley Error:", "Volley Error:" + volleyError.getMessage());
Toast.makeText(getActivity(), "Unable to connect to server, try again later", Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
})

{
@Override
protected Map<String, String> getParams() throws AuthFailureError {

Map<String, String> params = new HashMap<String, String>();
// params.put("uniquesessiontokenid", "39676161-b890-4d10-8c96-7aa3d9724119");
params.put("uniquesessiontokenid", userDet.getSessionToken());
params.put("said", userDet.getSAID());
params.put("SOId", "23295");

return super.getParams();
}

@Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse networkResponse) {

try {
String jsonString = new String(networkResponse.data,
HttpHeaderParser
.parseCharset(networkResponse.headers));
return Response.success(new JSONArray(jsonString),
HttpHeaderParser
.parseCacheHeaders(networkResponse));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}

// return null;
}
}
);

Volley - Sending a POST request using JSONArrayRequest

They're probably going to add it later, but in the meanwhile you can add the wanted constructor yourself:

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

This isn't tested, though I see no reason this shouldn't work since the implementation details are in the super class: JsonRequest.

Try it and see if it works.

EDIT:

I called it! It took them almost two years after I answered this but the Volley team added this constructor on March 19, 2015 to the repo. Guess what? This is the EXACT syntax.



Related Topics



Leave a reply



Submit