OkHttp贴身为JSON

所以,当我使用Koush的Ion时,我可以通过一个简单的.setJsonObjectBody(json).asJsonObject()为我的post添加一个json主体。

我正在转向OkHttp,我真的没有看到这样做的好方法。 我得到了400错误的地方。

有人有主意吗?

我甚至尝试手动格式化为jsonstring。

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

编辑:任何人稍后绊倒这个问题,这是我的解决scheme,asynchronous做任何事情。 所选答案是正确的,但我的代码有点不同。

 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的好处只是…工作。

Solutions Collecting From Web of "OkHttp贴身为JSON"

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

另一种方法是使用FormBody.Builder()
这里是一个callback的例子:

 Callback loginCallback = new Callback() { @Override public void onFailure(Call call, IOException e) { try { Log.i(TAG, "login failed: " + call.execute().code()); } catch (IOException e1) { e1.printStackTrace(); } } @Override public void onResponse(Call call, Response response) throws IOException { // String loginResponseString = response.body().string(); try { JSONObject responseObj = new JSONObject(response.body().string()); Log.i(TAG, "responseObj: " + responseObj); } catch (JSONException e) { e.printStackTrace(); } // Log.i(TAG, "loginResponseString: " + loginResponseString); } }; 

然后,我们创build自己的身体:

 RequestBody formBody = new FormBody.Builder() .add("username", userName) .add("password", password) .add("customCredential", "") .add("isPersistent", "true") .add("setCookie", "true") .build(); OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(this) .build(); Request request = new Request.Builder() .url(loginUrl) .post(formBody) .build(); 

最后,我们称之为服务器:

 client.newCall(request).enqueue(loginCallback);