OkHttp Post Body as JSON

匿名 (未验证) 提交于 2019-12-03 03:06:01

问题:

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() {             @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() {         @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.

回答1:

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


回答2:

Another approach is by using FormBody.Builder().
Here's an example of 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);     } }; 

Then, we create our own body:

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

Finally, we call the server:

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


回答3:

You can create your own JSONObject then toString().

Remember run it in the background thread like doInBackground in AsyncTask.

   // create your json here    JSONObject jsonObject = new JSONObject();    try {        jsonObject.put("username", "yourEmail@com");        jsonObject.put("password", "yourPassword");        jsonObject.put("anyKey", "anyValue");     } catch (JSONException e) {        e.printStackTrace();    }    OkHttpClient client = new OkHttpClient();   MediaType JSON = MediaType.parse("application/json; charset=utf-8");   RequestBody body = RequestBody.create(JSON, jsonObject.toString());   Request request = new Request.Builder()                     .url("https://yourUrl/")                     .post(body)                     .build();    Response response = null;   try {       response = client.newCall(request).execute();       String resStr = response.body().string();   } catch (IOException e) {       e.printStackTrace();   } 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!