摘要:本文将带你了解Android应用开发Android 使用OKHttp3请求接口401,返回Authorization Required错误怎么解决,希望本文对大家学Android有所帮助。
本文将带你了解Android应用开发Android 使用OKHttp3请求接口401,返回Authorization Required错误怎么解决,希望本文对大家学Android有所帮助。
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;
}
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标移动开发之Android频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号