使用https/http协议登录后如何浏览网站(Java)

How can I browse web site after login using https/http protocol(in Java)

我正在尝试使用 Java 登录网站,我成功了。下面是我使用的代码。

    String query = "myquery";
    URL url = new URL(loginUrl);
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

    con.setRequestMethod("POST");
    con.setRequestProperty("Content-length", String.valueOf(query.length()));
    con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;Windows98;DigExt)");
    con.setDoOutput(true);
    con.setDoInput(true);

    DataOutputStream output = new DataOutputStream(con.getOutputStream());

    output.writeBytes(query);
    output.close();

    DataInputStream input = new DataInputStream( con.getInputStream() );

    for( int c = input.read(); c != -1; c = input.read() ) {
       System.out.print( (char)c );
       // this page returns JavaScript code
    }

在此之后,我想访问同一域中的另一个网页,所以我尝试了以下代码。

    URL url = new URL(anotherUrl);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();

    ... similar to above code ... 

但是这个页面要求我重新登录。我认为连接在更改过程中已断开URL。 (Onlt登录页面使用HTTPS协议,其他页面使用HTTP协议)

我该如何解决这个问题? 有人请帮忙

请记住,HTTP 是完全无状态的。 "logging in" 的想法转化为(通常)从 HTTP 角度设置 cookie。这些 cookie 只是 HTTP headers,它们随浏览器的每个后续请求一起发送。因此,要保持登录状态,您需要从响应中获取 cookie headers 并将它们与未来的请求一起发送。

方法如下:

正在从响应中检索 cookie:

打开一个java.net.URLConnection到服务器:

URL myUrl = new URL("http://www.hccp.org/cookieTest.jsp");
URLConnection urlConn = myUrl.openConnection();
urlConn.connect();

循环响应 headers 寻找 cookies: 由于服务器可能会在单个请求中设置多个 cookie,因此我们需要遍历响应 headers,查找所有名为 "Set-Cookie".

的 headers
String headerName=null;
for (int i=1; (headerName = uc.getHeaderFieldKey(i))!=null; i++) {
   if (headerName.equals("Set-Cookie")) {                  
    String cookie = urlConn.getHeaderField(i);               
    ...                                                      

从 cookie 字符串中提取 cookie 名称和值: getHeaderField(int index) 方法返回的字符串是由semi-colons(;)分隔的一系列name=value。第一个 name/value 对是我们感兴趣的实际数据字符串(即 "sessionId=0949eeee22222rtg" 或 "userId=igbrown"),随后的 name/value 对是 meta-information 我们将用于管理 cookie 的存储(当它过期时等)。

    cookie = cookie.substring(0, cookie.indexOf(";"));
    String cookieName = cookie.substring(0, cookie.indexOf("="));
    String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length());

基本上就是这样。我们现在有了 cookie 名称 (cookieName) 和 cookie 值 (cookieValue)。

在请求中设置 cookie 值:

必须在调用连接方法之前设置值:

 URL myUrl = new URL("http://www.hccp.org/cookieTest.jsp");
    URLConnection urlConn = myUrl.openConnection();

创建 cookie 字符串:

String myCookie = "userId=igbrown";

将 cookie 添加到请求中: 使用

setRequestProperty(字符串名称, 字符串值);

方法,我们将添加一个名为"Cookie"的属性,将上一步创建的cookie字符串作为属性值传递。

urlConn.setRequestProperty("Cookie", myCookie);

将cookie发送到服务器: 要发送 cookie,只需在我们为其添加 cookie 属性:

的 URLConnection 上调用 connect()
 urlConn.connect()