1

I am using okhttp3.RequestBody to send request to server, if I have JSONObject with data I need to send I am writing code like this:

RequestBody requestBody = new MultipartBody.Builder()
                                .setType(MultipartBody.FORM)
                                .addFormDataPart("id", object.optLong(Comment.TASK_ID_JSON_TAG) + "")
                                .addFormDataPart("type", "IMAGE")
                                .addFormDataPart("latitude", object.optDouble(Comment.LATITUDE_JSON_TAG) + "")
                                .addFormDataPart("longitude", object.optDouble(Comment.LONGITUDE_JSON_TAG) + "")
                                .build();

now if I have JSONObject with large data is there a way to create RequestBody directly?
thanks for help.

Tefa
  • 328
  • 1
  • 4
  • 15
  • please read these: [page1](http://stackoverflow.com/help/how-to-ask) [page2](http://stackoverflow.com/help/mcve) [page3](http://stackoverflow.com/help/on-topic) – Atef Hares Feb 21 '17 at 14:37
  • Ok, I did, what's the problem in my question? Is it not clear? – Tefa Feb 21 '17 at 14:45
  • Yes it is not clear, I adopt that any one will understands what you need. Instead provide your work and state what exactly you are trying to achieve – Atef Hares Feb 21 '17 at 15:03
  • I hope it's clear now. – Tefa Feb 21 '17 at 15:12

2 Answers2

1

Maybe you can post all json object in one param ,and send it to server.

check this out https://stackoverflow.com/a/34180100/1067963

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();
}
Community
  • 1
  • 1
xtr3mz
  • 73
  • 1
  • 10
0

You can use gson to serialize (gradle -> implementation group: 'com.google.code.gson', name: 'gson', version: '2.7' ) and then do this --> pay attention to MediaType and setbody function its just 2 lines of code :) and then send request use body... if you want to send java object as JSON do this

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

@Override
protected void setBody() {
    Gson gson = new Gson();
    String data = gson.toJson(yourObject);
    body = RequestBody.create(JSON, data);

}

//then you can build your request setting this body ( RequestBody body )

Shivam Kumar
  • 1,892
  • 2
  • 21
  • 33
La1M s
  • 1