Post over https using HttpUrlConnection

A

axel

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" +
"&param2=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
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,521
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top