某些API应该是服务器设置了限制,使得手机端okhttp作为 http客户端时,获取数据,服务器返回HTTP 403禁止访问。
本篇文章用修改okhttp的头部Header字段模拟手机浏览器访问服务器,从而可以通过被限制的服务器。
如果是未修改前,也就是默认时会出现
W/System.err: retrofit2.adapter.rxjava2.HttpException: HTTP 403 Forbidden
服务器禁止访问了,因为okhttp并不是真正的原生的http请求,它在header中并没有真正的User-Agent,而是“okhttp/版本号”。
开工。。。。。
获取User-Agent
在API17后可用下面这个来获取
WebSettings.getDefaultUserAgent(App.getINSTANCE())
给okHttp设置移除旧的Header并设置新的Header
- 如果是单纯的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,就要用构造器添加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;
}
}
end
参考自
网友评论