retrofit2.adapter.rxjava2.HttpException: HTTP 403 Forbidden
某些API應(yīng)該是服務(wù)器設(shè)置了限制,使得手機(jī)端okhttp作為 http客戶端時(shí),獲取數(shù)據(jù),服務(wù)器返回HTTP 403禁止訪問(wèn)。
服務(wù)器禁止訪問(wèn)了,因?yàn)閛khttp并不是真正的原生的http請(qǐng)求,它在header中并沒(méi)有真正的User-Agent,而是“okhttp/版本號(hào)”。
如果是單純的okHttp請(qǐng)求,不加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;
 ? ? }
 ? ? /**
 ? ? ?* ?構(gòu)造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;
 ? ? }
 }
附上常見(jiàn)瀏覽器User-Agent大全
參考:https://www.jianshu.com/p/4132b381f07e
參考:https://blog.csdn.net/dubo_csdn/article/details/90478831
總結(jié)
以上是生活随笔為你收集整理的retrofit2.adapter.rxjava2.HttpException: HTTP 403 Forbidden的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
                            
                        - 上一篇: 圆摆线帮助文件
 - 下一篇: Android数据编码之Base64