How to use HttpsURLConnection through proxy by setProperty?
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.
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();
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()
}
}