Post over https using HttpUrlConnection
Having problems getting a POST over https to work through a proxy. A
GET over http through the proxy works fine. A Post over https works
fine when not behind a proxy, but when behind a proxy then it does not
work:
javax.net.ssl.SSLHandshakeException: Remote host closed connection
during handshake.
Any help is appreciated.
Axel
Here a code snippet for the GET that works fine:
String site = "http://www.example.com";
try {
// with Proxy
URL url = new URL(
"http", // protocol
"proxyhostname", // host name or IP of proxy server
80, // proxy port
site); // URL
String userPassword = "domain\\user" + ":" + "password";
String encodedUserPassword = new BASE64Encoder()
.encode(userPassword.getBytes());
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Proxy-Authorization", "Basic "
+ encodedUserPassword);
InputStream in = con.getInputStream();
InputStreamReader inReader = new InputStreamReader(in);
BufferedReader bufReader = new BufferedReader(inReader);
String inputLine;
while ((inputLine = bufReader.readLine()) != null)
System.out.println(inputLine);
in.close();
} catch (Exception e) {
// exception handling
}
Here a code snippet that does not function:
String site = "https://www.example.com/dosomething";
try {
// with Proxy
URL url = new URL(
"https", // protocol
"proxyhostname", // host name or IP of proxy server
443, // proxy port
site); // URL
String userPassword = "domain\\user" + ":" + "password";
String encodedUserPassword = new BASE64Encoder()
.encode(userPassword.getBytes());
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Proxy-Authorization", "Basic "
+ encodedUserPassword);
String parametersAsString;
byte[] parametersAsBytes;
parametersAsString = "param1=value1" +
"¶m2=value2";
parametersAsBytes = parametersAsString.getBytes();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Length", "" +
Integer.toString(parametersAsBytes.length));
con.setUseCaches(false);
con.setDoInput(true);
con.setDoOutput(true);
OutputStream dataOut = con.getOutputStream();
dataOut.write(parametersAsBytes);
dataOut.flush();
dataOut.close();
InputStream in = con.getInputStream();
InputStreamReader inReader = new InputStreamReader(in);
BufferedReader bufReader = new BufferedReader(inReader);
String inputLine;
while ((inputLine = bufReader.readLine()) != null)
System.out.println(inputLine);
in.close();
} catch (Exception e) {
// exception handling
}