Android 使用OKHttp3請求接口401,返回Authorization Required錯誤怎麼解決

Android 使用OKHttp3請求接口401,返回Authorization Required錯誤怎麼解決,公司項目需要接入香港天文臺的天氣xml,API是https://xml.weather.gov.hk/V2/,需要賬號密碼,機場那邊提供過來之後,發現app內請求會報401,Authorization Required錯誤。

話不多說,直接上代碼:

OkHttpClient.Builder client = new OkHttpClient.Builder();
client.authenticator(new Authenticator() {
    @Override
    public Request authenticate(Route route, okhttp3.Response response) throws IOException {
        if (responseCount(response) >= 3) {
            return null; 
        }
        String credential = Credentials.basic("userName", "passWord");
        return response.request().newBuilder().header("Authorization", credential).build();
    }
});

Request request = new Request.Builder().get().url(url).build();
client.build().newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {

            }

            @Override
            public void onResponse(okhttp3.Call call, okhttp3.Response response) {
     		if (response.isSuccessful())
//                  LogUtils.error(TAG, "Successful");
                
            }
        });

private int responseCount(okhttp3.Response response) {
    int result = 1;
    while ((response = response.priorResponse()) != null) {
        result++;
    }
    return result;
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *