gpt4 book ai didi

android - 使用 Volley 发送带有 JSON 数据的 POST 请求

转载 作者:IT老高 更新时间:2023-10-28 13:09:30 24 4
gpt4 key购买 nike

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

  • 我想接收 JSON 数据(来自服务器的响应):好的
  • 我想用这个请求发送 JSON 格式的数据到服务器

    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 库。

最佳答案

JsonObjectRequest 实际上接受 JSONObject 作为正文。

来自 this blog article ,

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

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

这里是 source code and 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);
}

关于android - 使用 Volley 发送带有 JSON 数据的 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23220695/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com