在Retrofit+okHttp中设置修改http的访问头部User-Agent来解决某些API可以用电脑浏览器使用而不能在APP端使用的问题

某些API应该是服务器设置了限制,使得手机端okhttp作为 http客户端时,获取数据,服务器返回HTTP 403禁止访问。

本篇文章用修改okhttp的头部Header字段模拟手机浏览器访问服务器,从而可以通过被限制的服务器。

如果是未修改前,也就是默认时会出现

W/System.err: retrofit2.adapter.rxjava2.HttpException: HTTP 403 Forbidden

服务器禁止访问了,因为okhttp并不是真正的原生的http请求,它在header中并没有真正的User-Agent,而是“okhttp/版本号”。

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,就要用构造器添加Interceptor
  • import android.webkit.WebSettings; import com.minminaya.myapplication.App; import com.minminaya.myapplication.api.MusicApi; import java.io.IOException; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import retrofit2.CallAdapter; import retrofit2.Converter; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; * 初始化网络Retrofit等服务 * Created by Niwa on 2017/6/24. 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;