使用 Volley 发送带有 JSONArray 的 POST 请求 [英] Sending a POST request with JSONArray using Volley

查看:26
本文介绍了使用 Volley 发送带有 JSONArray 的 POST 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Android 中发送一个简单的 POST 请求,其正文等于:

<预><代码>[{价值":1}]

我尝试在 Android 中使用 Volley 库,这是我的代码:

//我要 POST 的 jsonArrayString json = "[{"value": 1}]";JSONArray jsonBody = null;尝试 {jsonBody = 新的 JSONArray(json);} catch (JSONException e) {e.printStackTrace();}最终 JSONArray finalJsonBody = jsonBody;//开始请求最终请求队列队列 = Volley.newRequestQueue(getApplicationContext());JsonObjectRequest 请求 =new JsonObjectRequest(com.android.volley.Request.Method.POST,"https://...",null,新的 Response.Listener() {@覆盖公共无效onResponse(JSONObject响应){Log.d("mytag", "响应为:" + response);}},新的 Response.ErrorListener() {@覆盖公共无效onErrorResponse(VolleyError错误){Log.d("Mytag", "error");}}) {@覆盖protected Map获取参数(){//问题就在这里...return (Map) finalJsonBody;}@覆盖公共地图<字符串,字符串>getHeaders() 抛出 AuthFailureError {HashMap<字符串,字符串>params = new HashMap();//我把我所有的标题都放在这里,如下所示:params.put("Content-Type", "application/json");返回参数;}};队列.添加(请求);

问题是 getParams 方法只接受一个 Map 对象,因为我想发送一个 JSONArray.所以,我不得不使用演员表,然后产生错误......

我不知道如何解决这个问题谢谢

解决方案

可以参考我下面的示例代码:

更新您的 pastebin 链接:

因为服务器响应 JSONArray,我使用 JsonArrayRequest 而不是 JsonObjectRequest.并且不再需要覆盖 getBody.

 mTextView = (TextView) findViewById(R.id.textView);字符串 url = "https://api.orange.com/datavenue/v1/datasources/2595aa553d3049f0b0f03fbaeaa7ddc7/streams/9fe5edb1c76e4968bdcc9c902010bc6c/values";RequestQueue requestQueue = Volley.newRequestQueue(this);最终字符串 jsonString = "[
" +" {
" +" "值": 1
" +" }
" +"]";尝试 {JSONArray jsonArray = new JSONArray(jsonString);JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, url, jsonArray, new Response.Listener() {@覆盖公共无效onResponse(JSONArray响应){mTextView.setText(response.toString());}}, 新的 Response.ErrorListener() {@覆盖公共无效onErrorResponse(VolleyError错误){mTextView.setText(error.toString());}}) {@覆盖公共地图<字符串,字符串>getHeaders() 抛出 AuthFailureError {映射<字符串,字符串>headers = new HashMap<>();headers.put("X-OAPI-Key","TQEEGSk8OgWlhteL8S8siKao2q6LIGdq");headers.put("X-ISS-Key","2b2dd0d9dbb54ef79b7ee978532bc823");返回标题;}};requestQueue.add(jsonArrayRequest);} catch (JSONException e) {e.printStackTrace();}

我的代码适用于 Google 的官方 volley 库和 mcxiaoke 的库

如果你想使用 Google 的库,在你 git clone 作为 Google 文档之后,从 srcmainjavacom 复制 android 文件夹(你克隆的 Volley 项目)到你的项目的 appsrcmainjavacom 如下截图:

build.gradle 应该包含以下内容

依赖项{编译文件树(目录:'libs',包括:['*.jar'])编译'com.android.support:appcompat-v7:23.0.1'编译'com.google.code.gson:gson:2.3.1'}

如果您的项目使用了mcxiaoke的库,build.gradle 将如下所示(注意dependencies):

应用插件:'com.android.application'安卓 {compileSdkVersion 23构建工具版本23.0.0"默认配置{applicationId "com.example.samplevolley"minSdk 版本 16目标SDK版本23版本代码 1版本名称1.0"}构建类型{发布 {minifyEnabled falseproguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'}}}依赖{编译文件树(目录:'libs',包括:['*.jar'])编译'com.android.support:appcompat-v7:23.0.0'编译'com.mcxiaoke.volley:library:1.0.17'编译'com.google.code.gson:gson:2.3'}

我建议您新建两个示例项目,一个使用Google的库,另一个使用mcxiaoke的库.

更新结束

 String url = "http://...";RequestQueue requestQueue = Volley.newRequestQueue(this);最终字符串 jsonString = "[
" +" {
" +" "值": 1
" +" }
" +"]";JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener() {@覆盖公共无效onResponse(JSONObject响应){//做一点事...}}, 新的 Response.ErrorListener() {@覆盖公共无效onErrorResponse(VolleyError错误){//做一点事...}}) {@覆盖公共字节[] getBody() {尝试 {返回 jsonString.getBytes(PROTOCOL_CHARSET);} catch (UnsupportedEncodingException uee) {VolleyLog.wtf("尝试使用 %s 获取 %s 的字节时不支持编码",jsonString, PROTOCOL_CHARSET);返回空;}}};requestQueue.add(jsonObjectRequest);

以下截图是服务器端web服务收到的内容:

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 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'm obliged to use a cast, which generate an error then...

I don't know how can I fix that Thank you

解决方案

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 = "[
" +
                " {
" +
                "  "value": 1
" +
                " }
" +
                "]";
        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 srcmainjavacom (of Volley project that you cloned) to appsrcmainjavacom of your project as the following screenshot:

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 = "[
" +
                " {
" +
                "  "value": 1
" +
                " }
" +
                "]";
        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:

这篇关于使用 Volley 发送带有 JSONArray 的 POST 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆