nifCody
nifCody

Reputation: 2444

Sending JSON body through POST request in OKhttp in Android

I have setting up OkHttpClient and successfully sending the GET request to the server. And also I could able to sending the POST request to the server with empty body tag.

Now, I'm trying to send the following JSON Object to the server.

{
"title": "Mr.",
"first_name":"Nifras",
"last_name": "",
"email": "[email protected]",
"contact_number": "75832366",
"billing_address": "",
"connected_via":"Application"
}

For this I have trying to adding the OkHttpClient library class RequestBody but I fail to sending the JSON object as body of the http POST request. The following way I have try to build the body and process the post request.

OkHttpClient client = new OkHttpClient();

    RequestBody body = new RequestBody() {
        @Override
        public MediaType contentType() {
            return ApplicationContants.JSON;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
              // This is the place to add json I thought. But How could i do this
        }
    };

    Request request = new Request.Builder()
            .url(ApplicationContants.BASE_URL + ApplicationContants.CUSTOMER_URL)
            .post(body)
            .build();

What is the way I send the JSON object to the server via POST request.

Thanks in advance.

Upvotes: 8

Views: 24794

Answers (2)

Mable John
Mable John

Reputation: 5238

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

Upvotes: 13

Kelevandos
Kelevandos

Reputation: 7082

Just do this:

@Override
public 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.

Upvotes: 1

Related Questions