怎样才能在java代码中登陆一个网站,然后获得该网站的内容?
我知道用java.net.URL可以获得网站的内容,但是当一个网站需要登陆以后才能查看的话我应该怎样做到呢?

解决方案 »

  1.   

    (1)java里保存cookie
    (2)有个开源项目:httpClient
      

  2.   

    cookie的方法类似于下面:这个能否使用依赖于服务器的实现。
            URL url = new URL("http://hostname:80");
            URLConnection conn = url.openConnection();
            conn.setRequestProperty("Cookie", "name1=value1; name2=value2");
            conn.connect();建议看看httpClient。
      

  3.   

    上面没说清楚。
    用cookie方法
    (1)模拟登陆,获取cookies
            URL url = new URL("http://hostname:80");
            URLConnection conn = url.openConnection();        for (int i=0; ; i++) {
                String headerName = conn.getHeaderFieldKey(i);
                String headerValue = conn.getHeaderField(i);
        
                if (headerName == null && headerValue == null) {
                    break;
                }
                if ("Set-Cookie".equalsIgnoreCase(headerName)) {
                    String[] fields = headerValue.split(";\\s*");
        
                    String cookieValue = fields[0];
                    String expires = null;
                    String path = null;
                    String domain = null;
                    boolean secure = false;
       
                    for (int j=1; j<fields.length; j++) {
                        if ("secure".equalsIgnoreCase(fields[j])) {
                            secure = true;
                        } else if (fields[j].indexOf('=') > 0) {
                            String[] f = fields[j].split("=");
                            if ("expires".equalsIgnoreCase(f[0])) {
                                expires = f[1];
                            } else if ("domain".equalsIgnoreCase(f[0])) {
                                domain = f[1];
                            } else if ("path".equalsIgnoreCase(f[0])) {
                                path = f[1];
                            }
                        }
                    }            }
            }(2)取得cookies之后,请求新页面都带上cookie,就是上面回复的那个例子。就可以了。
    具体代码自己看着办吧,原理是这样
      

  4.   

    可能楼主的意思是用session而不是cookie