Working with HttpsURLConnection
843790May 10 2010 — edited May 20 2010Hi,
Im using the code below to connect to a https server from java .
It validates the username and password but it doesnt redirect or goto the homepage when the inputstream is read
DataInputStream input = new DataInputStream( connection.getInputStream() );
always has the same html code from the login page even after the login has been successful .(I was expecting the html page of the user's "home").
I tried opening the connection to a new url(the actual servlet running home page of the user) but it didnt go through..(It again gave back the html code of the login page)
Could you please help me figure out a way to navigate through the website.
From login page to home page to page 2 etc using java https ?
Please find the source code below.
Greatly appreciate the help.
Thanks,
JJ
Source code:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Properties;
import com.sun.net.ssl.HttpsURLConnection;
public class test {
public static void main(String[] args){
try {
Properties sysProperties = System.getProperties();
sysProperties.put("proxy_type", "4");
sysProperties.put("proxyHost", "..");
sysProperties.put("proxyPort", "8080");
sysProperties.put("proxySet", "true");
System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
URL url = new URL("..");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("POST");
System.out.println("the opencon was successful");
connection.setDoOutput(true);
connection.setDoInput(true);
System.out.println("doip doop --yes");
connection.setUseCaches(false);
connection.setDefaultUseCaches(false);
String query = "j_username=" + URLEncoder.encode("..");
query += "&";
query += "j_password=" + URLEncoder.encode("..");
connection.setAllowUserInteraction(true);
connection.setRequestProperty ("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" + query.length());
connection.setRequestMethod("POST");
HttpsURLConnection.setFollowRedirects(true);
connection.setInstanceFollowRedirects(true);
connection.connect();
// open up the output stream of the connection
DataOutputStream output = new DataOutputStream( connection.getOutputStream() );
String content =query;
output.writeBytes (content);
output.flush ();
System.out.println("Resp Code:"+connection.getResponseCode());
System.out.println("Resp Message:"+ connection.getResponseMessage());
output.close();
DataInputStream input = new DataInputStream( connection.getInputStream() );
//read in each character until end-of-stream is detected
for( int c = input.read(); c != -1; c = input.read() )
System.out.print( (char)c );
input.close();
}
catch(Exception e)
{
System.out.println( e );
e.printStackTrace();
}
}
}