2011-11-23 48 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);