相关疑难解决方法(0)

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

我想发一个新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;
            }
        };
    
    Run Code Online (Sandbox Code Playgroud)

PS我也在我的项目中使用GSON库.

android http-post android-volley android-json

81
推荐指数
4
解决办法
16万
查看次数

OkHttp Post Body as JSON

所以,当我使用Koush的Ion时,我能够通过一个简单的方式在我的帖子中添加一个json体 .setJsonObjectBody(json).asJsonObject()

我正在转向OkHttp,我真的没有看到一个很好的方法来做到这一点.我到处都收到错误400.

有人有主意吗?

我甚至尝试将其手动格式化为json字符串.

String reason = menuItem.getTitle().toString();
JsonObject json = new JsonObject();
json.addProperty("Reason", reason);

String url = mBaseUrl + "/" + id + "/report";

Request request = new Request.Builder()
        .header("X-Client-Type", "Android")
        .url(url)
        .post(RequestBody
                .create(MediaType
                    .parse("application/json"),
                        "{\"Reason\": \"" + reason + "\"}"
                ))
        .build();

client.newCall(request).enqueue(new com.squareup.okhttp.Callback() {
    @Override
    public void onFailure(Request request, IOException throwable) {
        throwable.printStackTrace();
    }

    @Override
    public void onResponse(Response response) throws IOException {
        if (!response.isSuccessful()) throw new IOException(
                "Unexpected code " + response);
        runOnUiThread(new Runnable() {
            @Override …
Run Code Online (Sandbox Code Playgroud)

android json http-post android-ion okhttp

60
推荐指数
4
解决办法
9万
查看次数