How to get JSON values that Okhttp generated?

Asked

Viewed 119 times

-1

This is my code

public void loginRequestAsync() {

    OkHttpClient client = new OkHttpClient();

    HttpUrl.Builder urlBuilder = HttpUrl.parse("xxx.xxxx.xx.x.xx.xxx.x").newBuilder();
    String url = urlBuilder.build().toString();
    RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("ddi", String.valueOf(ddi.getText()))
            .addFormDataPart("numero", String.valueOf(numero.getText()))
            .build();

    Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Log.d("Response: ",response.body().string());

        }
    });
}
  • Provide more information for help!

  • I need to get the values that are printed in the log

1 answer

0

You can use the Httplogginginterceptor. After including the library in your project, simply add it as a Interceptor in his OkHttpClient:

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
  .addInterceptor(logging)
  .build();

When using Level.BODY, the body of requests and responses will appear in your log. Output example:

--> POST /greeting http/1.1
Host: example.com
Content-Type: plain/text
Content-Length: 3

Hi?
--> END POST

<-- 200 OK (22ms)
Content-Type: plain/text
Content-Length: 6

Hello!
<-- END HTTP

This tool should be used carefully as it can expose sensitive data.

  • and if I want to save the log data in another class how can I do it? ?

  • It is possible to pass a Httplogginginterceptor.Logger customized by instantiating the Httplogginginterceptor. The Httplogginginterceptor.Logger interface defines a single method log, that receives messages displayed on the console.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.