开发者

Java HttpClient problem with Cookies

I use Apache HttpClient to first Request a page for the Cookies, and then post to a page with those Cookies. To be able to get the second page, the Cookie must be sent with the post. I've read somewhere that HttpClient automatically saves and Sends the needed Cookies, but somehow I keep stuck at the first page, probably due to Cookies not being get properly, or not being sent properly.

 public class Main {

static BufferedWriter writer;

public static void main(String args[]) throws ClientProtocolException, IOException {

    getRequest();
}

pub开发者_JAVA技巧lic static void getRequest() throws ClientProtocolException, IOException {

    HttpClient client = new DefaultHttpClient();

    //the request to get the Cookies
    HttpGet request = new HttpGet("http://www.SiteNameCutOut.cz");

    List <NameValuePair> parameters = new ArrayList <NameValuePair>();  
    parameters.add(new BasicNameValuePair("view_state", "eaftOTAPef3NDs79"));  
    parameters.add(new BasicNameValuePair("age", "23"));  
    parameters.add(new BasicNameValuePair("button", "go"));  

    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters);
    HttpPost post = new HttpPost("http://www.SameSiteAsAbove.cz");
    post.setEntity(entity);


    //post.addHeader(request.getFirstHeader("Set-Cookie")); maybe?
    post.addHeader("Host","theSiteHost");
    post.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.0; rv:2.0.1) Gecko/20100101 Firefox/4.0.1");
    post.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    post.addHeader("Accept-Language","en-us,en;q=0.5");
    post.addHeader("Accept-Encoding","gzip, deflate");
    post.addHeader("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    post.addHeader("Keep-Alive","115");
    post.addHeader("Connection","keep-alive");


    client.execute(request);

    try {
        request.abort();
        HttpResponse response = client.execute(post);
        writer = new BufferedWriter(new FileWriter("test001.html"));
        writer.write(HttpHelper.request(response)); //gets html of the response
    } catch (IOException ex) {
        System.out.println("**Error**");
    } finally {
        if(writer != null){
            writer.close();
        }
        else{
            System.out.println("Writer is null");
        }
    }
}

}

So i hope anyone can help me, Thanks !


You should indicate how to manage the cookies like this:

request.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜