0

I'm making calls to the server using okhttp

For some debug calls, I need to trust all the certificates, but although I have read answers on how to do it, I have not managed to implement it.

My code for making this call without including anything yet about trusting all the certifications is:

public class Handler_JSON_get_accept_auth {

    public Handler_JSON_get_accept_auth() {
    }

    public String makeServiceCall(String url, String auth) {
        final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(45, TimeUnit.SECONDS);
        client.setReadTimeout(45, TimeUnit.SECONDS);
        client.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
        Request request = new Request.Builder()
                .url(url)
                .header("Accept","application/json")
                .header("Authorization",auth)
                .get()
                .build();
        try {
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (Exception e) {
            e.printStackTrace();
            // Time out
            return null;
        }
    }
}

I have seen this answer in this same forum and it is considered correct:

Trusting all certificates with okHttp

unfortunately, I do not know how to implement this solution to my code, and this is taking me a long time.

I would appreciate any help to implement it.

Thanks and regards.

Sergio76
  • 3,835
  • 16
  • 61
  • 88

1 Answers1

1

Try to use OkHttpClient.Builder instead of direct OkHttpClient. Then you can setup sslSocketFactory and hostnameVerifier described https://stackoverflow.com/a/25992879/3816129

Dmytro Batyuk
  • 957
  • 8
  • 15
  • It seems the right answer, but I have a problem, the line of code: Response response = builder.newCall (request) .execute (); indicates error on newcall (can not resolve method newcall (com.squareup.okhttp.Request) .. Any idea? I do not see any incompatibilities – Sergio76 Jun 19 '19 at 13:03
  • after setting ssl socket factory just call build of builder and you get an instance of OkHttpClient which you can use in same way you did before. Does it work? – Dmytro Batyuk Jun 19 '19 at 13:33