Android http 403 错误 可能出现的原因

  • Post author:
  • Post category:其他


今天自己写代码使用Retrofit下载百度搜索出来的图片的时候,发现了报错了,403。然后使用Glide却可以加载图片。

然后对Glide进行抓包,发现Glide请求的时候 http header 是这种格式的:

User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36

而我自己的 请求默认是

User-Agent: okhttp/3.10.0

估计是百度对User-Agent有要求,所以我自己添加了一个正常的User-Agent请求头就ok了。


public class UserAgentInterceptor  implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request()
                .newBuilder()
                .removeHeader("User-Agent")//移除旧的
                .addHeader("User-Agent", WebSettings.getDefaultUserAgent(MyApplication.getInstance()))//添加真正的头部,可以写死,也可以动态获取
                .build();
        return chain.proceed(request);
    }
}
 HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        if (mOkHttpClient == null) {
            synchronized (RetrofitClient.class) {
                if (mOkHttpClient == null) {
                    //设置Http缓存
                    //Cache cache = new Cache(new File(BilibiliApp.getInstance().getCacheDir(), "HttpCache"), 1024 * 1024 * 10);
                    mOkHttpClient = new OkHttpClient.Builder()
                            //.cache(cache)
                            .addInterceptor(interceptor)
                            .addInterceptor(new UserAgentInterceptor())
                            //.addNetworkInterceptor(new CacheInterceptor())
                            //.addNetworkInterceptor(new StethoInterceptor())
                            .retryOnConnectionFailure(true)
                            .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                            .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                            .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                            .cookieJar(new CookieManger(context))
                            //.addInterceptor(new UserAgentInterceptor())
                            .build();
                }
            }
        }



版权声明:本文为ai_te_xiao原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。