OkHttp Post Body as JSON [英] OkHttp Post Body as JSON

查看:633
本文介绍了OkHttp Post Body as JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,当我使用Koush的Ion时,我能够使用简单的 .setJsonObjectBody(json).asJsonObject() <添加一个json正文到我的帖子/ p>

我正在转向OkHttp,我真的没有看到这样做的好方法。我到处都收到错误400.



任何人有什么想法吗?



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

  String reason = menuItem.getTitle()。toString(); 
JsonObject json = new JsonObject();
json.addProperty(理由,原因);

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

请求请求=新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(请求请求,IOException throwable){
throwable.printStackTrace();
}

@Override
public void onResponse(响应响应)抛出IOException {
if(!response.isSuccessful()抛出新的IOException(
意外的代码+响应);
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(理由,原因);

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

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

请求请求=新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(请求请求,IOException throwable){
throwable.printStackTrace();
}

@Override
public void onResponse(响应响应)抛出IOException {
if(!response.isSuccessful()抛出新的IOException(
意外的代码+响应);
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的好处......工作。

解决方案

只需使用 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)抛出IOException {
RequestBody body = RequestBody.create(JSON,json);
请求请求=新Request.Builder()
.url(url)
.post(正文)
.build();
响应响应= client.newCall(request).execute();
返回response.body()。string();
}


So, back when I was using Koush's Ion, I was able to add a json body to my posts with a simple .setJsonObjectBody(json).asJsonObject()

I'm moving over to OkHttp, and I really don't see a good way to do that. I'm getting error 400's all over the place.

Anyone have any ideas?

I've even tried manually formatting it as a json string.

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();
            }
        });*/

Edit: For anyone stumbling upon this question later, here is my solution that does everything asynchronously. The selected answer IS CORRECT, but my code is a bit different.

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);
}

A little more work, mainly because you have to get back to the UI thread to do any UI work, but you have the benefit of HTTPS just...working.

解决方案

Just use JSONObject.toString(); method. And have a look at OkHttp's tutorial:

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);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}

这篇关于OkHttp Post Body as JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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