Sending a POST request using JSONArray using Volley

I want to send a simple POST request in Android with a body equal to this:

[ { "value": 1 } ] 

I tried using the Volley library on Android, and this is my code:

 // the jsonArray that I want to POST String json = "[{\"value\": 1}]"; JSONArray jsonBody = null; try { jsonBody = new JSONArray(json); } catch (JSONException e) { e.printStackTrace(); } final JSONArray finalJsonBody = jsonBody; // starting the request final RequestQueue queue = Volley.newRequestQueue(getApplicationContext()); JsonObjectRequest request = new JsonObjectRequest(com.android.volley.Request.Method.POST,"https://...",null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d("mytag", "Response is: " + response);}}, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d("Mytag", "error");}}) { @Override protected Map<String,String> getParams() { // the problem is here... return (Map<String, String>) finalJsonBody; } @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> params = new HashMap<String, String>(); // I put all my headers here like the following one : params.put("Content-Type", "application/json"); return params;}}; queue.add(request); 

The problem is that the getParams method only accepts a Map object, since I want to send a JSONArray. So, I must use a cast that generates an error, then ...

I do not know how I can fix this. Thank you.

+5
source share
1 answer

You can reference my following code example:

UPDATE for your pastebin link:

Since the server is responding with JSONArray , I use JsonArrayRequest instead of JsonObjectRequest . And no need to override getBody .

  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 both for the official volley libray library and for mcxiaoke google.

If you want to use the Google library, after git cloning as Google documentation, copy the android folder from \src\main\java\com (from the project you cloned) to \app\src\main\java\com your project as the next screenshot:

enter image description here

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 the mcxiaoke library, build.gradle will look like this (note the 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 you create 2 new sample projects, then the Google library will be used, the other will use the mcxiaoke 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 the server side web service received:

enter image description here

+4
source

Source: https://habr.com/ru/post/1232118/


All Articles