Reputation: 346
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.
Upvotes: 2
Views: 14995
Reputation: 11
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 )
Upvotes: 1
Reputation: 73
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();
}
Upvotes: 1