#StackBounty: #android #certificate #okhttp Use a certificate in an okhttp request with android

Bounty: 200

The server of the application in which I work uses a certificate to allow requests.
I have it installed, for example, in the desktop Chrome browser and it works fine. It´s a usual certificate with the extension .cer

Now I have to make this certificate work also in my android application and, honestly, I have never done it and I’m a bit lost.

To make the requests I am using okhttp2, as you can see in this example:

 public String makeServiceCall(String url, JSONObject data) {
        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));

        RequestBody body = RequestBody.create(JSON, data.toString());
        Request request = new Request.Builder()
                .url(url)
                .header("Accept","application/json")
                .post(body)
                .build();
        try {
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

So far everything works perfectly, but after searching and reading tutorials, examples, etc, (many of them from this page) I have not managed to make it work. Make it work with the certificate.

Having never done this, and being a bit confused already, I would appreciate the following clarifications:

  • The certificate in .cer format that I have, I suppose I should convert it to another format to be able to use it in android …
    Is it correct? If it is correct, how should I do it?

ok, I already have my certificate converted to BKS and hosted in the res / raw folder, but I’m still unable to apply it successfully to the request okhttp2 ..

  • Once with a certificate in correct format,
    How is it implemented with the requests that I am already making in the code that I have set as an example?

I have searched for information about doing it using okhttp3 but I have not been able to authorize the requests either.

This article has been useful to me, but I am not using retrofit and adapting it to okhttp2 does not work either.

I would appreciate an explanation of how to do it


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.