OkHttp Post Body as JSON












47















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.










share|improve this question

























  • is your url contain "http://" at start?

    – Android Android
    Dec 9 '15 at 13:36











  • https://, actually, but yes

    – Pixel Perfect
    Dec 9 '15 at 13:48











  • Have you trusted certificates for your app?

    – Android Android
    Dec 9 '15 at 13:51











  • Well, seeing as I get {"Reason":"Inappropriate"} Response{protocol=http/1.1, code=200, message=OK, url=api/id/report} {"Reason":"Copyright"} Response{protocol=http/1.1, code=400, message=Bad Request, url=api/id/report} 23 min

    – Pixel Perfect
    Dec 9 '15 at 14:34











  • it took out my https:// for the url=

    – Pixel Perfect
    Dec 9 '15 at 14:35
















47















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.










share|improve this question

























  • is your url contain "http://" at start?

    – Android Android
    Dec 9 '15 at 13:36











  • https://, actually, but yes

    – Pixel Perfect
    Dec 9 '15 at 13:48











  • Have you trusted certificates for your app?

    – Android Android
    Dec 9 '15 at 13:51











  • Well, seeing as I get {"Reason":"Inappropriate"} Response{protocol=http/1.1, code=200, message=OK, url=api/id/report} {"Reason":"Copyright"} Response{protocol=http/1.1, code=400, message=Bad Request, url=api/id/report} 23 min

    – Pixel Perfect
    Dec 9 '15 at 14:34











  • it took out my https:// for the url=

    – Pixel Perfect
    Dec 9 '15 at 14:35














47












47








47


17






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.










share|improve this question
















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.







android json http-post okhttp ion






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 10 '15 at 13:08







Pixel Perfect

















asked Dec 9 '15 at 13:22









Pixel PerfectPixel Perfect

4311412




4311412













  • is your url contain "http://" at start?

    – Android Android
    Dec 9 '15 at 13:36











  • https://, actually, but yes

    – Pixel Perfect
    Dec 9 '15 at 13:48











  • Have you trusted certificates for your app?

    – Android Android
    Dec 9 '15 at 13:51











  • Well, seeing as I get {"Reason":"Inappropriate"} Response{protocol=http/1.1, code=200, message=OK, url=api/id/report} {"Reason":"Copyright"} Response{protocol=http/1.1, code=400, message=Bad Request, url=api/id/report} 23 min

    – Pixel Perfect
    Dec 9 '15 at 14:34











  • it took out my https:// for the url=

    – Pixel Perfect
    Dec 9 '15 at 14:35



















  • is your url contain "http://" at start?

    – Android Android
    Dec 9 '15 at 13:36











  • https://, actually, but yes

    – Pixel Perfect
    Dec 9 '15 at 13:48











  • Have you trusted certificates for your app?

    – Android Android
    Dec 9 '15 at 13:51











  • Well, seeing as I get {"Reason":"Inappropriate"} Response{protocol=http/1.1, code=200, message=OK, url=api/id/report} {"Reason":"Copyright"} Response{protocol=http/1.1, code=400, message=Bad Request, url=api/id/report} 23 min

    – Pixel Perfect
    Dec 9 '15 at 14:34











  • it took out my https:// for the url=

    – Pixel Perfect
    Dec 9 '15 at 14:35

















is your url contain "http://" at start?

– Android Android
Dec 9 '15 at 13:36





is your url contain "http://" at start?

– Android Android
Dec 9 '15 at 13:36













https://, actually, but yes

– Pixel Perfect
Dec 9 '15 at 13:48





https://, actually, but yes

– Pixel Perfect
Dec 9 '15 at 13:48













Have you trusted certificates for your app?

– Android Android
Dec 9 '15 at 13:51





Have you trusted certificates for your app?

– Android Android
Dec 9 '15 at 13:51













Well, seeing as I get {"Reason":"Inappropriate"} Response{protocol=http/1.1, code=200, message=OK, url=api/id/report} {"Reason":"Copyright"} Response{protocol=http/1.1, code=400, message=Bad Request, url=api/id/report} 23 min

– Pixel Perfect
Dec 9 '15 at 14:34





Well, seeing as I get {"Reason":"Inappropriate"} Response{protocol=http/1.1, code=200, message=OK, url=api/id/report} {"Reason":"Copyright"} Response{protocol=http/1.1, code=400, message=Bad Request, url=api/id/report} 23 min

– Pixel Perfect
Dec 9 '15 at 14:34













it took out my https:// for the url=

– Pixel Perfect
Dec 9 '15 at 14:35





it took out my https:// for the url=

– Pixel Perfect
Dec 9 '15 at 14:35












3 Answers
3






active

oldest

votes


















94














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





share|improve this answer
























  • Well, I need to see if the backend is even working properly. Your code acts identically to mine - crashing when I supply one thing for the string in the JSON, but working when I supply something different.

    – Pixel Perfect
    Dec 9 '15 at 13:59











  • Turns out, my issue was just that my JSON data itself was wrong. I was supplying an incorrect string. "Copyright".equals("CopyrightInfringement") returns false

    – Pixel Perfect
    Dec 10 '15 at 12:57











  • i want to send different data....json array with normal data..how can i?

    – H Raval
    Mar 8 '16 at 10:27



















7














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





share|improve this answer


























  • Thanks, this answer work for me very well. But I have a question, what would be the best approach to sending an extra parameter with JSON type. This is how the request works image, and this is how I sending the RequestBody information image. The code works well but I receive an error from the response telling me that the Image parameter was incorrect. Maybe I need to turn into an object and parse to String?. Thanks in advance

    – Martín Daniel
    May 16 '17 at 19:25





















4














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");
// put your json here
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();
}





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f34179922%2fokhttp-post-body-as-json%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    94














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





    share|improve this answer
























    • Well, I need to see if the backend is even working properly. Your code acts identically to mine - crashing when I supply one thing for the string in the JSON, but working when I supply something different.

      – Pixel Perfect
      Dec 9 '15 at 13:59











    • Turns out, my issue was just that my JSON data itself was wrong. I was supplying an incorrect string. "Copyright".equals("CopyrightInfringement") returns false

      – Pixel Perfect
      Dec 10 '15 at 12:57











    • i want to send different data....json array with normal data..how can i?

      – H Raval
      Mar 8 '16 at 10:27
















    94














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





    share|improve this answer
























    • Well, I need to see if the backend is even working properly. Your code acts identically to mine - crashing when I supply one thing for the string in the JSON, but working when I supply something different.

      – Pixel Perfect
      Dec 9 '15 at 13:59











    • Turns out, my issue was just that my JSON data itself was wrong. I was supplying an incorrect string. "Copyright".equals("CopyrightInfringement") returns false

      – Pixel Perfect
      Dec 10 '15 at 12:57











    • i want to send different data....json array with normal data..how can i?

      – H Raval
      Mar 8 '16 at 10:27














    94












    94








    94







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





    share|improve this answer













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






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Dec 9 '15 at 13:32









    Ostap AndrusivOstap Andrusiv

    3,4752733




    3,4752733













    • Well, I need to see if the backend is even working properly. Your code acts identically to mine - crashing when I supply one thing for the string in the JSON, but working when I supply something different.

      – Pixel Perfect
      Dec 9 '15 at 13:59











    • Turns out, my issue was just that my JSON data itself was wrong. I was supplying an incorrect string. "Copyright".equals("CopyrightInfringement") returns false

      – Pixel Perfect
      Dec 10 '15 at 12:57











    • i want to send different data....json array with normal data..how can i?

      – H Raval
      Mar 8 '16 at 10:27



















    • Well, I need to see if the backend is even working properly. Your code acts identically to mine - crashing when I supply one thing for the string in the JSON, but working when I supply something different.

      – Pixel Perfect
      Dec 9 '15 at 13:59











    • Turns out, my issue was just that my JSON data itself was wrong. I was supplying an incorrect string. "Copyright".equals("CopyrightInfringement") returns false

      – Pixel Perfect
      Dec 10 '15 at 12:57











    • i want to send different data....json array with normal data..how can i?

      – H Raval
      Mar 8 '16 at 10:27

















    Well, I need to see if the backend is even working properly. Your code acts identically to mine - crashing when I supply one thing for the string in the JSON, but working when I supply something different.

    – Pixel Perfect
    Dec 9 '15 at 13:59





    Well, I need to see if the backend is even working properly. Your code acts identically to mine - crashing when I supply one thing for the string in the JSON, but working when I supply something different.

    – Pixel Perfect
    Dec 9 '15 at 13:59













    Turns out, my issue was just that my JSON data itself was wrong. I was supplying an incorrect string. "Copyright".equals("CopyrightInfringement") returns false

    – Pixel Perfect
    Dec 10 '15 at 12:57





    Turns out, my issue was just that my JSON data itself was wrong. I was supplying an incorrect string. "Copyright".equals("CopyrightInfringement") returns false

    – Pixel Perfect
    Dec 10 '15 at 12:57













    i want to send different data....json array with normal data..how can i?

    – H Raval
    Mar 8 '16 at 10:27





    i want to send different data....json array with normal data..how can i?

    – H Raval
    Mar 8 '16 at 10:27













    7














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





    share|improve this answer


























    • Thanks, this answer work for me very well. But I have a question, what would be the best approach to sending an extra parameter with JSON type. This is how the request works image, and this is how I sending the RequestBody information image. The code works well but I receive an error from the response telling me that the Image parameter was incorrect. Maybe I need to turn into an object and parse to String?. Thanks in advance

      – Martín Daniel
      May 16 '17 at 19:25


















    7














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





    share|improve this answer


























    • Thanks, this answer work for me very well. But I have a question, what would be the best approach to sending an extra parameter with JSON type. This is how the request works image, and this is how I sending the RequestBody information image. The code works well but I receive an error from the response telling me that the Image parameter was incorrect. Maybe I need to turn into an object and parse to String?. Thanks in advance

      – Martín Daniel
      May 16 '17 at 19:25
















    7












    7








    7







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





    share|improve this answer















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






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jul 17 '16 at 20:38









    Fllo

    10.6k53483




    10.6k53483










    answered Jun 5 '16 at 13:58









    AbdulMomen عبدالمؤمنAbdulMomen عبدالمؤمن

    2,15822639




    2,15822639













    • Thanks, this answer work for me very well. But I have a question, what would be the best approach to sending an extra parameter with JSON type. This is how the request works image, and this is how I sending the RequestBody information image. The code works well but I receive an error from the response telling me that the Image parameter was incorrect. Maybe I need to turn into an object and parse to String?. Thanks in advance

      – Martín Daniel
      May 16 '17 at 19:25





















    • Thanks, this answer work for me very well. But I have a question, what would be the best approach to sending an extra parameter with JSON type. This is how the request works image, and this is how I sending the RequestBody information image. The code works well but I receive an error from the response telling me that the Image parameter was incorrect. Maybe I need to turn into an object and parse to String?. Thanks in advance

      – Martín Daniel
      May 16 '17 at 19:25



















    Thanks, this answer work for me very well. But I have a question, what would be the best approach to sending an extra parameter with JSON type. This is how the request works image, and this is how I sending the RequestBody information image. The code works well but I receive an error from the response telling me that the Image parameter was incorrect. Maybe I need to turn into an object and parse to String?. Thanks in advance

    – Martín Daniel
    May 16 '17 at 19:25







    Thanks, this answer work for me very well. But I have a question, what would be the best approach to sending an extra parameter with JSON type. This is how the request works image, and this is how I sending the RequestBody information image. The code works well but I receive an error from the response telling me that the Image parameter was incorrect. Maybe I need to turn into an object and parse to String?. Thanks in advance

    – Martín Daniel
    May 16 '17 at 19:25













    4














    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");
    // put your json here
    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();
    }





    share|improve this answer






























      4














      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");
      // put your json here
      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();
      }





      share|improve this answer




























        4












        4








        4







        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");
        // put your json here
        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();
        }





        share|improve this answer















        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");
        // put your json here
        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();
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Aug 27 '18 at 19:19

























        answered Jan 29 '18 at 11:44









        Allen WangAllen Wang

        35728




        35728






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f34179922%2fokhttp-post-body-as-json%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Coverage of Google Street View

            Full-time equivalent

            Surfing