代码之家  ›  专栏  ›  技术社区  ›  dharga

使用Java URL连接关闭Cookie

  •  8
  • dharga  · 技术社区  · 17 年前

    我正在尝试向需要cookies的网页发出请求。我正在使用HTTPUrlConnection,但是回复总是说

    <div class="body"><p>Your browser's cookie functionality is turned off. Please turn it on.
    

    如何发出请求,使被查询的服务器认为我打开了cookie。我的代码是这样的。

    private String readPage(String page) throws MalformedURLException {
        try {
            URL url = new URL(page);
            HttpURLConnection uc = (HttpURLConnection) url.openConnection();
            uc.connect();
    
            InputStream in = uc.getInputStream();
            int v;
            while( (v = in.read()) != -1){
                sb.append((char)v);
            }
            in.close();
            uc.disconnect();
        } catch (IOException e){
            e.printStackTrace();
        }
        return sb.toString();
    }
    
    4 回复  |  直到 17 年前
        1
  •  11
  •   ZZ Coder    17 年前

    您需要将CookieHandler添加到系统中,以便处理cookie。在Java6之前,JRE中没有CookieHandler实现,您必须自己编写。如果您使用的是Java 6,您可以这样做,

      CookieHandler.setDefault(new CookieManager());
    

    URLConnection的cookie处理非常弱。它几乎不起作用。它不能正确处理所有cookie规则。如果您正在处理敏感cookie(如身份验证),则应使用ApacheHttpClient。

        2
  •  2
  •   Serge Bogatyrev    17 年前

    我认为服务器无法在第一次请求时确定客户端不支持cookies。所以,服务器可能会发送重定向。尝试禁用重定向:

    uc.setInstanceFollowRedirects(false);
    

        3
  •  2
  •   Allen Rice 0x6A75616E    15 年前
    uc.getHeaderFields()
    // get cookie (set-cookie) here
    
    URLConnection conn = url.openConnection();
    conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; pl; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2");
    conn.addRequestProperty("Referer", "http://xxxx");
    conn.addRequestProperty("Cookie", "...");
    
        4
  •  -4
  •   Alex Marshall    17 年前

    如果您试图在登录后刮取大量数据,那么使用WebHarvest这样的脚本式web刮取器可能会更好( http://web-harvest.sourceforge.net/