Skip to content Skip to sidebar Skip to footer

Sending A Post Request With Jsonarray Using Volley

I want to send a simple POST request in Android with a body equaling this : [ { 'value': 1 } ] I tried to use Volley library in Android, and this is my code : // the jsonArr

Solution 1:

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 = newJSONArray(jsonString);
            JsonArrayRequest jsonArrayRequest = newJsonArrayRequest(Request.Method.POST, url, jsonArray, newResponse.Listener<JSONArray>() {
                @OverridepublicvoidonResponse(JSONArray response) {
                    mTextView.setText(response.toString());
                }
            }, newResponse.ErrorListener() {
                @OverridepublicvoidonErrorResponse(VolleyError error) {
                    mTextView.setText(error.toString());
                }
            }) {
                @OverridepublicMap<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> headers = newHashMap<>();
                    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:

enter image description here

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 = newJsonObjectRequest(Request.Method.POST, url, null, newResponse.Listener<JSONObject>() {
            @OverridepublicvoidonResponse(JSONObject response) {
                // do something...
            }
        }, newResponse.ErrorListener() {
            @OverridepublicvoidonErrorResponse(VolleyError error) {
                // do something...
            }
        }) {
            @Overridepublic 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);
                    returnnull;
                }
            }
        };
        requestQueue.add(jsonObjectRequest);

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

enter image description here

Post a Comment for "Sending A Post Request With Jsonarray Using Volley"