Re: [Htmlparser-user] Cookie
Brought to you by:
derrickoswald
From: Bob L. <bob...@ya...> - 2003-03-12 16:41:01
|
In order to send cookies in your Http requests, all you need to do is set the Cookie HTTP Header in the URL Connection. Generally what I've done is first create a HttpURLConnection, create some Cookie objects that are needed, and set the HTTP Header using those objects (See below for code to format the header value). Then I'll create the Parser using the URLConnection something like this: DefaultHTMLParserFeedback feedback = new DefaultHTMLParserFeedback(DefaultHTMLParserFeedback.DEBUG); HTMLReader reader = null; HTMLParser parser = null; String charset = HttpUtil.getCharacterSet(urlConn); InputStreamReader isr = new InputStreamReader(urlConn.getInputStream(), charset); reader = new HTMLReader(isr, 8192); parser = new HTMLParser(reader, feedback); The HttpUtil.getCharacterSet method used above is basically just taken from the method of the same name in the HTMLParser class. That method is protected, so I had to duplicate it elsewhere. /** set cookies to send in a HttpURLConnection<br> * This method should only be called before any parameters are posted * and before the connection is made. * @param urlConn the HttpURLConnection to send the cookies through * @param cookies the cookies to send */ public static void postCookies(HttpURLConnection urlConn, Cookie[] cookies) { if ((cookies == null) || (cookies.length == 0)) { return; } String[] cookieHeaders = new String[cookies.length]; urlConn.setRequestProperty("cookie", generateCookieHeader(cookies)); } /** generate a HTTP cookie header value string from an array of cookies * @param cookies the cookies which should be set in the header value * @return A string containing the HTTP Cookie Header value */ private static String generateCookieHeader(Cookie[] cookies) { StringBuffer buf = new StringBuffer(); for (int i=0; i < cookies.length;i++) { buf.append(cookies[i].getName()); buf.append("="); buf.append(cookies[i].getValue()); if (i+1 != cookies.length) { buf.append("; "); } else buf.append(" "); } return buf.toString(); } --- Shan Sivakolundhu <vss...@ya...> wrote: > > Hi, > > In order to access a particular site I neet to have > a cookie set. Is there any way I can set the cookie > before I create a parser object ? Just like ... > > URLConnection.("Cookie", cookieValue); > > URLConnection.connect(); > > > > Regards, > > Shan > > > > --------------------------------- > Do you Yahoo!? > Yahoo! Web Hosting - establish your business online __________________________________________________ Do you Yahoo!? Yahoo! Web Hosting - establish your business online http://webhosting.yahoo.com |