发送使用乱射JSONArray POST请求乱射、JSONArray、POST

2023-09-13 02:01:05 作者:唯我独萌ii

我想在Android中发送一个简单的POST请求与身体等于这样的:

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

[
 {
  "value": 1
 }
]

我试图用排枪库在Android中,这是我的code:

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

现在的问题是,该getParams能够方法只接受一个Map对象,因为我想送一个JSONArray。所以,我不得不使用一个演员,这产生一个错误,那么...

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

推荐答案

您可以参考我下面的示例code:

You can refer to my following sample code:

更新你的引擎收录链接:

由于服务器响应的 JSONArray ,我用 JsonArrayRequest 而不是 JsonObjectRequest 。而且不需要重写 getBody 了。

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

我的code同时适用于谷歌的官方凌空libray和mcxiaoke的库

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

如果你想使用谷歌的图书馆,你的Git后如谷歌文档克隆,复制机器人文件夹从的\ src \主\的java \ COM (那你克隆排球项目) \程序\ SRC \主\ java的\ COM 项目如下截图:

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:

build.gradle 应包含以下

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

如果您的项目使用的 mcxiaoke 的图书馆,在 build.gradle 将如下所示(注意依赖):

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

我建议你将创建两个新的样本项目,那么人们会使用谷歌的图书馆,对方会使用 mcxiaoke 的库。

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

下面的截图是收到什么样的服务器端Web服务:

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