Sending JSON body through POST request in OKhttp in Android Sending JSON body through POST request in OKhttp in Android json json

Sending JSON body through POST request in OKhttp in Android


Try this

Add Gradle depends compile 'com.squareup.okhttp3:okhttp:3.2.0'

public static JSONObject foo(String url, JSONObject json) {        JSONObject jsonObjectResp = null;        try {            MediaType JSON = MediaType.parse("application/json; charset=utf-8");            OkHttpClient client = new OkHttpClient();            okhttp3.RequestBody body = RequestBody.create(JSON, json.toString());            okhttp3.Request request = new okhttp3.Request.Builder()                    .url(url)                    .post(body)                    .build();            okhttp3.Response response = client.newCall(request).execute();            String networkResp = response.body().string();            if (!networkResp.isEmpty()) {                jsonObjectResp = parseJSONStringToJSONObject(networkResp);            }        } catch (Exception ex) {            String err = String.format("{\"result\":\"false\",\"error\":\"%s\"}", ex.getMessage());            jsonObjectResp = parseJSONStringToJSONObject(err);        }        return jsonObjectResp;    }

Parse Response

   private static JSONObject parseJSONStringToJSONObject(final String strr) {    JSONObject response = null;    try {        response = new JSONObject(strr);    } catch (Exception ex) {        //  Log.e("Could not parse malformed JSON: \"" + json + "\"");        try {            response = new JSONObject();            response.put("result", "failed");            response.put("data", strr);            response.put("error", ex.getMessage());        } catch (Exception exx) {        }    }    return response;}


Just do this:

@Overridepublic void writeTo(BufferedSink sink) throws IOException {     sink.writeUtf8(yourJsonString); }

And it should work fine :-) If I understand the documentation correctly, sink is a container into which you can write the data you want to post. The writeUtf8 method is convenience for turning the String into bytes, using the UTF-8 encoding.