如何使用带有字符串正文的 volley 发送 POST 请求?
我正在开发一个 Android 应用程序,该应用程序与我编写的 RESTful Web 服务进行通信.将 Volley
用于 GET
方法非常棒且简单,但我无法将手指放在 POST
方法上.
I'm developing an Android app that communicate with a RESTful web service I wrote. Using Volley
for GET
methods is awesome and easy, but I can't put my finger on the POST
methods.
我想在请求正文中发送一个带有 String
的 POST
请求,并检索 Web 服务的原始响应(例如 200 ok
, 500 服务器错误
).
I want to send a POST
request with a String
in the body of the request, and retrieve the raw response of the web service (like 200 ok
, 500 server error
).
我能找到的只是StringRequest
,它不允许发送数据(正文),而且它限制我接收解析的String
响应.我还遇到了 JsonObjectRequest
它接受数据(正文)但检索解析的 JSONObject
响应.
All I could find is the StringRequest
which doesn't allow to send with data (body), and also it bounds me to receive a parsed String
response.
I also came across JsonObjectRequest
which accepts data (body) but retrieve a parsed JSONObject
response.
我决定编写自己的实现,但找不到从 Web 服务接收原始响应的方法.我该怎么做?
I decided to write my own implementation, but I cannot find a way to receive the raw response from the web service. How can I do it?
可以参考以下代码(当然你可以自定义获取更多网络响应的细节):
You can refer to the following code (of course you can customize to get more details of the network response):
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://...";
JSONObject jsonBody = new JSONObject();
jsonBody.put("Title", "Android Volley Demo");
jsonBody.put("Author", "BNK");
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
@Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
@Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}