1

I got this code:

And it gets executed as follows : new SendFdToApi().execute();

private class SendFdToApi extends AsyncTask<URL, Integer, Long> {
        @Override
        protected Long doInBackground(URL... urls) {

            Gson gson = new GsonBuilder().create();
            String jsonObj = gson.toJson(fdReq);

            OkHttpClient client = getUnsafeOkHttpClient();
            RequestBody body;
            Request request;

            MediaType mediaType = MediaType.parse("application/json; charset=UTF-8");
            body = RequestBody.create(mediaType, jsonObj);
            request = new Request.Builder()
                    .url("url")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json; charset=UTF-8")
                    .build();

            try {
                Response response = client.newCall(request).execute();

                //------Get response message here--------

            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e){
                e.printStackTrace();
            }
            return null;
        }
    }
}

After the request is sent I am expecting a JSON message as a result but I don't know how to get the response from the response variable which is an okhttp3.Response type.

This is what my API returns: return new JsonResult(new { mesagge = "message", status = "S" });

Bani
  • 542
  • 4
  • 20
  • This should give you an answer. https://stackoverflow.com/questions/2591098/how-to-parse-json-in-java. and if so should this be considered a duplicate? – Chris Feb 28 '23 at 09:36
  • @Chris The `response` is an `okhttp3.Response` so `new JSONObject(response)` does not work. – Bani Feb 28 '23 at 09:39
  • Does this answer your question? [How to parse JSON in Java](https://stackoverflow.com/questions/2591098/how-to-parse-json-in-java) – user2357113 Feb 28 '23 at 10:13
  • @mujammil someone already suggested that and it doesn't solve my issue – Bani Feb 28 '23 at 10:25

1 Answers1

1

To get the response from body I had to use this:

String jsonData = response.body().string();
JSONObject Jobject = new JSONObject(jsonData);

and then I have the Json object returned from the API call.

Bani
  • 542
  • 4
  • 20