Okhttp或HttpURLConnect添加代理

时间:2019-02-25 11:28:22

标签: android okhttp

我的代码在android 7.0+中运行,可以,但是在6.0或5.0 okhttp中,向我显示此错误:

  

java.net.UnknownHostException:主机尚未解析:222.85.91.56

HttpUrlConnect什么也不显示

我已经在AndroidManifest.xml中写了权限

我的代码:

    private void testHttpURLConnect(){
        URL url = new URL("https://123.85.91.6");
        InetSocketAddress isa = new InetSocketAddress("61.135.122.82", 1080 );
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(new Proxy(Proxy.Type.SOCKS, isa));
        conn.setRequestMethod("POST");
        conn.setSSLSocketFactory(SSLSocketClient.getSSLSocketFactory());
        conn.setHostnameVerifier(SSLSocketClient.getHostnameVerifier());
        conn.connect();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        if((line = reader.readLine()) != null){
            Log.e("Tag" , line);
        }

}

private void myTestOkhttp(){
    InetSocketAddress isa = new InetSocketAddress("61.135.122.82", 1080 );
    OkHttpClient client = new OkHttpClient.Builder()
            .proxy(new Proxy(Proxy.Type.SOCKS, isa))
            .sslSocketFactory(SSLSocketClient.getSSLSocketFactory())//配置
            .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
            .build();

    Request request = new Request.Builder().url("https://123.85.91.6").post(new FormBody.Builder().build()).build();
    client.newCall(request).enqueue(new okhttp3.Callback() {
        @Override
        public void onFailure(okhttp3.Call call, IOException e) {
            Log.e("tag" , "onfaile");
            e.printStackTrace();
        }

        @Override
        public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
            Log.e("tag" , "response : " + response.body().string());
        }
    });
}

我的英语不好:(

0 个答案:

没有答案