重点说明
提示说明这篇文章并未完全搞定https代理,经过几次的修改测试也只是搞定了其中一种场景
1.无账户认证代理 (搞定)
2.需账户认证代理 (未搞定)
正文
public class ProxyUtils{
public static void initProxy() {
HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("代理地址", 代理端口号));
OkHttpClient.Builder builder = new OkHttpClient
.Builder()
.connectTimeout(30000L, TimeUnit.MILLISECONDS) //设置连接超时
.readTimeout(30000L, TimeUnit.MILLISECONDS) //设置读取超时
.proxy(proxy)
.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
Log.i("PROXY_VERIFY", hostname);
return true; //此处一定要置为true
}
})
.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager) //设置SSL
.addInterceptor(interceptor);//设置拦截器
OkHttpClient okHttpClient = builder.build();
try {
Class o = Class.forName("com.zhy.http.okhttp.OkHttpUtils");
Field field = o.getDeclaredField("mOkHttpClient");
field.setAccessible(true);
field.set(OkHttpUtils.getInstance(), okHttpClient);
} catch (Exception ignored) {
}
}
}
public class Test{
public void callPrxoy(){
ProxyUtils.initProxy();
Request.Builder builder = new Request.Builder();
builder.addHeader("添加头部信息") //这一步可以放在拦截器中去做
.post(body) //添加body
.url("https://www.baidu.com"); //设置https访问地址
OkHttpUtils.getInstance()
.getOkHttpClient()
.newCall(builder.build())
.enqueue(callback); //定制回调
}