使用 Volley 使用 JSONArray 发送 POST 请求
Sending a POST request with JSONArray using Volley
我想在 Android 中发送一个简单的 POST 请求,正文等于:
[
{
"value": 1
}
]
我尝试在 Android 中使用 Volley 库,这是我的代码:
// 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。所以,我不得不使用强制转换,然后会产生错误...
我不知道该如何解决
谢谢
你可以参考我下面的示例代码:
更新你的 pastebin link:
因为服务器响应 JSONArray
,所以我使用 JsonArrayRequest
而不是 JsonObjectRequest
。无需再覆盖 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();
}
我的代码适用于 Google 的官方 volley 库和 mcxiaoke 的库
如果你想使用Google的库,在你git克隆为Google文档后,复制android 文件夹从 \src\main\java\com
(您克隆的 Volley 项目)到您项目的 \app\src\main\java\com
,如下图所示:
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
会像下面这样(注意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'
}
我建议你创建2个新的示例项目,然后一个使用Google的库,另一个使用mcxiaoke的图书馆。
更新结束
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);
服务器端网络服务收到的截图如下:
我想在 Android 中发送一个简单的 POST 请求,正文等于:
[
{
"value": 1
}
]
我尝试在 Android 中使用 Volley 库,这是我的代码:
// 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。所以,我不得不使用强制转换,然后会产生错误...
我不知道该如何解决 谢谢
你可以参考我下面的示例代码:
更新你的 pastebin link:
因为服务器响应 JSONArray
,所以我使用 JsonArrayRequest
而不是 JsonObjectRequest
。无需再覆盖 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();
}
我的代码适用于 Google 的官方 volley 库和 mcxiaoke 的库
如果你想使用Google的库,在你git克隆为Google文档后,复制android 文件夹从 \src\main\java\com
(您克隆的 Volley 项目)到您项目的 \app\src\main\java\com
,如下图所示:
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
会像下面这样(注意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'
}
我建议你创建2个新的示例项目,然后一个使用Google的库,另一个使用mcxiaoke的图书馆。
更新结束
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);
服务器端网络服务收到的截图如下: