How to use HttpsURLConnection through proxy by setProperty?

前端 未结 3 1471
梦如初夏
梦如初夏 2020-12-10 03:29

Network environment:

Https Client<=============>Proxy Server<==============>Https Server
       

相关标签:
3条回答
  • 2020-12-10 03:34

    thank you @divinedragon!

    Same code on kotlin:

     fun testProxy(login: String, pass: String, proxyData: ProxyData): String {
        val url = URL("http://api.ipify.org")
        val proxy = Proxy(Proxy.Type.HTTP, InetSocketAddress(proxyData.ip, proxyData.port))
        val connection = url.openConnection(proxy) as HttpURLConnection
    
        val loginPass = "$login:$pass"
        val encodedLoginPass = Base64.getEncoder().encodeToString(loginPass.toByteArray())
        val authString = "Basic $encodedLoginPass"
        connection.setRequestProperty("Proxy-Authorization", authString);
        with(connection) {
            requestMethod = "GET"  // optional default is GET
            connectTimeout = 2000
            readTimeout = 2000
            return inputStream.bufferedReader().readText()
        }
    }
    
    0 讨论(0)
  • 2020-12-10 03:36

    Your URL connection is https whereas you are only setting the http proxy.

    Try setting the https proxy.

    //System.setProperty("https.proxySet", "true"); 
     System.setProperty("https.proxyHost",10.100.21.11);
     System.setProperty("https.proxyPort","443");
    

    EDIT @EJP is correct. There is no https.proxySet .. I copied your original question and included in the answer.

    0 讨论(0)
  • 2020-12-10 03:42

    You will need to create a Proxy object for it. Create one as below:

    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyServer, Integer.parseInt(proxyPort)));
    

    Now use this proxy to create the HttpURLConnection object.

    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(proxy);
    

    If you have to set the credentials for the proxy, set the Proxy-Authorization request property:

    String uname_pwd = proxyUsername + ":" + proxyPassword
    String authString = "Basic " + new sun.misc.BASE64Encoder().encode(uname_pwd.getBytes())
    connection.setRequestProperty("Proxy-Authorization", authString);
    

    And finally, you connect:

    connection.connect();
    
    0 讨论(0)
提交回复
热议问题