使用 Volley 发送带有 JSON 数据的 POST 请求 [英] Send POST request with JSON data using Volley

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

问题描述

我想发送一个新的 JsonObjectRequest 请求:

I would like to send a new JsonObjectRequest request:

  • 我想接收 JSON 数据(来自服务器的响应):好的
  • 我想将带有此请求的 JSON 格式的数据发送到服务器

  • I want to receive JSON data (response from server): OK
  • I want to send JSON formatted data with this request to the server

JsonObjectRequest request = new JsonObjectRequest(
    Request.Method.POST, "myurl.com", null,
    new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            //...
        }
    },
    new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            //...
        }
    })
    {
        @Override
        protected Map<String,String> getParams() {
            // something to do here ??
            return params;
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            // something to do here ??
            return params;
        }
    };

附言我的项目中也使用了 GSON 库.

P.S. I use GSON library in my project too.

推荐答案

JsonObjectRequest 实际上接受 JSONObject 作为主体.

JsonObjectRequest actually accepts JSONObject as body.

来自这篇博客文章

final String url = "some/url";
final JSONObject jsonBody = new JSONObject("{"type":"example"}");

new JsonObjectRequest(url, jsonBody, new Response.Listener<JSONObject>() { ... });

这是源代码和JavaDoc (@param jsonRequest):

/**
 * Creates a new request.
 * @param method the HTTP method to use
 * @param url URL to fetch the JSON from
 * @param jsonRequest A {@link JSONObject} to post with the request. Null is allowed and
 *   indicates no parameters will be posted along with request.
 * @param listener Listener to receive the JSON response
 * @param errorListener Error listener, or null to ignore errors.
 */
public JsonObjectRequest(int method, String url, JSONObject jsonRequest,
        Listener<JSONObject> listener, ErrorListener errorListener) {
    super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
                errorListener);
}

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

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