2011-11-23 124 views
4

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

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: Connection closed by peer

如果我使用url.OpenConnection()wuithout代理和无Proxysettings在APN,代码工作,可能是什么问题?

回答

3

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

Properties systemSettings=System.getProperties(); 

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

作品,感谢°! – 2red13

+1

@CommonWare,我认为第三方应用程序不能从代码中设置代理,因为它没有权限。代理设置仅用于系统应用程序。所以您的建议是否真的有效?仅适用于移动网络还是适用于WiFi?谢谢。 – Safecoder

+0

@HowardLi:我的建议只影响你自己的应用程序。 – CommonsWare

1

可以使用NetCipher库使用Android的HttpsURLConnection时候才能轻松代理设置和现代化的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);