Android OkHttp with Basic Authentication

后端 未结 12 1530
感动是毒
感动是毒 2020-12-07 12:58

I\'m using the OkHttp library for a new project and am impressed with its ease of use. I now have a need to use Basic Authentication. Unfortunately, there is a dearth of w

12条回答
  •  太阳男子
    2020-12-07 13:46

    The aforementioned solution has one drawback: httpClient adds authorization headers only after receiving 401 response. Here's how my communication with api-server looked like:

    If you need to use basic-auth for every request, better add your auth-headers to each request or use a wrapper method like this:

    private Request addBasicAuthHeaders(Request request) {
        final String login = "your_login";
        final String password = "p@s$w0rd";
        String credential = Credentials.basic(login, password);
        return request.newBuilder().header("Authorization", credential).build();
    }
    

提交回复
热议问题