HttpsUrlConnection with Proxy

时间:2011-11-23 08:58:58

标签: android web-applications ssl proxy

我有一个使用HttpsUrlConnection执行POST请求的代码,代码工作正常,但我的一些用户拥有一个封闭用户组的SIM卡,他们需要在他们的apn设置中设置代理。如果他们设置代理,我需要修改我的代码。我试过这个:

    HttpsURLConnection connection = null;
    DataOutputStream outputStream = null;
    DataInputStream inputStream = null;
    String urlServer = "https://xxx";
    String boundary = "*****";

try {

    URL url = new URL(urlServer);
    SocketAddress sa = new InetSocketAddress("[MY PROXY HOST]",[My PROXY PORT]);
    Proxy mProxy = new Proxy(Proxy.Type.HTTP, sa);

    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;boundary=" + boundary);

    //this is supposed to open the connection via proxy
    //if i use url.openConnection() instead, the code works
    connection = (HttpsURLConnection) url.openConnection(mProxy);

    //the following line will fail
    outputStream = new DataOutputStream(connection.getOutputStream());

    // [...] 

} catch (Exception ex) {
   ret = ex.getMessage();
}

现在我收到错误:

  

javax.net.ssl.SSLException:由peer

关闭的连接

如果我在apn中使用url.OpenConnection()wuithout Proxy而没有Proxysettings,代码可以工作,可能是什么问题?

2 个答案:

答案 0 :(得分:3)

您可以尝试这种注册代理服务器的替代方法:

Properties systemSettings=System.getProperties();

systemSettings.put("http.proxyHost", "your.proxy.host.here");
systemSettings.put("http.proxyPort", "8080"); // use actual proxy port

答案 1 :(得分:1)

使用Android的HttpsURLConnection时,您可以使用NetCipher库轻松进行代理设置和现代TLS配置。致电NetCipher.setProxy()以设置应用全局代理。 NetCipher还将HttpsURLConnection实例配置为使用支持最佳的TLS版本,删除SSLv3支持,并为该TLS版本配置最佳密码套件。首先,将其添加到 build.gradle

compile 'info.guardianproject.netcipher:netcipher:1.2'

或者您可以下载 netcipher-1.2.jar 并将其直接包含在您的应用中。然后而不是呼叫:

HttpURLConnection connection = (HttpURLConnection) sourceUrl.openConnection(mProxy);

请致电:

NetCipher.setProxy(mProxy);
HttpURLConnection connection = NetCipher.getHttpURLConnection(sourceUrl);