如何使用带字符串主体的凌空发送POST请求? [英] How to send a POST request using volley with string body?

查看:77
本文介绍了如何使用带字符串主体的凌空发送POST请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个与我编写的RESTful Web服务通信的Android应用.将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.

我想发送带有正文中的StringPOST请求,并检索Web服务的原始响应(如200 ok500 server error).

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

这篇关于如何使用带字符串主体的凌空发送POST请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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