发送POST请求使用凌空JSON数据 [英] Send POST request with JSON data using Volley

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

问题描述

我想送一个新的 JsonObjectRequest 要求:

  • 我想收到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;
        }
    };

P.S。我用在我的项目也GSON库。

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

推荐答案

JsonObjectRequest 实际上接受的JSONObject 之身。

这篇博客文章

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

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

下面是<一href="https://android.googlesource.com/platform/frameworks/volley/+/master/src/com/android/volley/toolbox/JsonObjectRequest.java">source code和JavaDoc的( @参数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);
}

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

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