小编典典

OkHttp发布正文为JSON

json

所以,当我使用Koush的离子时,我能够使用一个简单的方法将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
            public void run() {
                Toast.makeText(context, "Report Received", Toast.LENGTH_SHORT).show();
            }
        });
    }
});

/*Ion.with(getContext(), url)
        .setHeader("X-Client-Type", "Android")
        .setJsonObjectBody(json)
        .asJsonObject()
        .setCallback(new FutureCallback<JsonObject>() {
            @Override
            public void onCompleted(Exception e, JsonObject result) {
                Toast.makeText(context, "Report Received", Toast.LENGTH_SHORT).show();
            }
        });*/

编辑:对于以后在这个问题上遇到麻烦的人,这是我的解决方案,它异步执行所有操作。所选答案正确,但是我的代码有些不同。

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

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

String jsonString = json.toString();
RequestBody body = RequestBody.create(JSON, jsonString);

Request request = new Request.Builder()
    .header("X-Client-Type", "Android")
    .url(url)
    .post(body)
    .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
            public void run() {
                Toast.makeText(context, "Report Received", Toast.LENGTH_SHORT).show();
            }
        });
    }
});

/*Ion.with(getContext(), url)
    .setHeader("X-Client-Type", "Android")
    .setJsonObjectBody(json)
    .asJsonObject()
    .setCallback(new FutureCallback<JsonObject>() {
        @Override
        public void onCompleted(Exception e, JsonObject result) {
            Toast.makeText(context, "Report Received", Toast.LENGTH_SHORT).show();
        }
    });*/

...

private void runOnUiThread(Runnable task) {
    new Handler(Looper.getMainLooper()).post(task);
}

要做更多的工作,主要是因为您必须回到UI线程才能执行任何UI工作,但是HTTPS的好处就是……可以工作。


阅读 238

收藏
2020-07-27

共1个答案

小编典典

只需使用JSONObject.toString();
方法。看看OkHttp的教程:

public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(json, JSON); // new
  // RequestBody body = RequestBody.create(JSON, json); // old
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}
2020-07-27