retrofit2.adapter.rxjava2.HttpException: HTTP 403 Forbidden

  • Post author:
  • Post category:java


某些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