HttpsUrlConnection代理设置

4
我有一段代码,用于使用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: 连接被对等方关闭

如果我在apn中不使用代理和代理设置,直接使用url.OpenConnection(),那么代码可以正常运行,可能是什么问题呢?

2个回答

3
您可以尝试使用以下替代方式注册代理服务器:
Properties systemSettings=System.getProperties();

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

1
@CommonWare,我认为第三方应用程序无法从其代码中设置代理,因为它没有权限。代理设置仅保留给系统应用程序使用。那么,您的建议真的有效吗?它只适用于移动网络还是也适用于WiFi?谢谢。 - Safecoder
@HowardLi:我的建议只会影响到你自己的应用程序。 - CommonsWare
@CommonsWare,感谢您的澄清。Android如何处理代理确实令人困惑。我猜如果我在我的应用程序中放置类似这样的内容,并且用户在其Android的wifi或移动设置中设置了不同的代理,则这两个代理将被链接?我在Android代理上发布了一个更一般的问题http://stackoverflow.com/questions/9139080/android-proxy-wifi-vs-mobile 您介意对此发表评论吗? - Safecoder

1
你可以使用NetCipher库来轻松设置代理和现代的TLS配置,当使用Android的HttpsURLConnection时。调用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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接