I have this working code that sends a POST request to my API:
private class ApiDataSender extends AsyncTask<URL, Integer, Long> {
@Override
protected Long doInBackground(URL... urls) {
Gson gsonParser = new GsonBuilder().create();
String requestJson = gsonParser.toJson(dataRequest);
OkHttpClient httpClient = createHttpClient();
RequestBody requestBody;
Request apiRequest;
MediaType jsonType = MediaType.parse("application/json; charset=UTF-8");
requestBody = RequestBody.create(jsonType, requestJson);
apiRequest = new Request.Builder()
.url("my-api-endpoint")
.method("POST", requestBody)
.addHeader("Content-Type", "application/json; charset=UTF-8")
.build();
try {
Response apiResponse = httpClient.newCall(apiRequest).execute();
//------Need to parse response data here--------
} catch (IOException ex) {
ex.printStackTrace();
} catch (Exception ex){
ex.printStackTrace();
}
return null;
}
}
I execute this with new ApiDataSender().execute()
My server returns JSON like this: return new JsonResult(new { message = "success", status = "OK" })
The problem is I don’t know how to get the actual JSON string from the apiResponse variable which is of type okhttp3.Response. What method should I use to read the response body content?