retrofit2.adapter.rxjava2.HttpException: HTTP 403 Forbidden
某些API應該是服務器設置了限制,使得手機端okhttp作為 http客戶端時,獲取數據,服務器返回HTTP 403禁止訪問。
服務器禁止訪問了,因為okhttp并不是真正的原生的http請求,它在header中并沒有真正的User-Agent,而是“okhttp/版本號”。
如果是單純的okHttp請求,不加Retrofit的
Request request = new Request.Builder().url(url)
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?.removeHeader("User-Agent")
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?.addHeader("User-Agent", WebSettings.getDefaultUserAgent(App.getINSTANCE()))
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? .build();
? ? ? ? ? ? httpClient.newCall(request).enqueue(handler);
如果是okHttp+Retrofit
public class NetWork {
?
? ? private static MusicApi musicApi;
? ? private static Converter.Factory gsonConverterFactory = GsonConverterFactory.create();
? ? private static CallAdapter.Factory rxJavaCallAdapterFactory = RxJava2CallAdapterFactory.create();
?
?
? ? public static MusicApi getMusicApi() {
? ? ? ? if (musicApi == null) {
? ? ? ? ? ? Retrofit retrofit = new Retrofit.Builder()
? ? ? ? ? ? ? ? ? ? .client(getOkHttpClient())//獲取后的okhttp頭部
? ? ? ? ? ? ? ? ? ? .baseUrl("http://tingapi.ting.baidu.com/v1/restserver/")
? ? ? ? ? ? ? ? ? ? .addConverterFactory(gsonConverterFactory)
? ? ? ? ? ? ? ? ? ? .addCallAdapterFactory(rxJavaCallAdapterFactory)
? ? ? ? ? ? ? ? ? ? .build();
? ? ? ? ? ? musicApi = retrofit.create(MusicApi.class);
? ? ? ? }
? ? ? ? return musicApi;
? ? }
? ? /**
? ? ?* ?構造okhttp頭部
? ? ?*
? ? ?* */
? ? private static OkHttpClient getOkHttpClient() {
? ? ? ? OkHttpClient httpClient = new OkHttpClient.Builder()
? ? ? ? ? ? ? ? .addInterceptor(new Interceptor() {
? ? ? ? ? ? ? ? ? ? @Override
? ? ? ? ? ? ? ? ? ? public Response intercept(Chain chain) throws IOException {
? ? ? ? ? ? ? ? ? ? ? ? Request request = chain.request()
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? .newBuilder()
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? .removeHeader("User-Agent")//移除舊的
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? .addHeader("User-Agent", WebSettings.getDefaultUserAgent(App.getINSTANCE()))//添加真正的頭部
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? .build();
? ? ? ? ? ? ? ? ? ? ? ? return chain.proceed(request);
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }).build();
? ? ? ? return httpClient;
? ? }
}
附上常見瀏覽器User-Agent大全
參考:https://www.jianshu.com/p/4132b381f07e
參考:https://blog.csdn.net/dubo_csdn/article/details/90478831
總結
以上是生活随笔為你收集整理的retrofit2.adapter.rxjava2.HttpException: HTTP 403 Forbidden的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 圆摆线帮助文件
- 下一篇: excel模板批量导入数据