In these day, I am write a client to access web. But I met issue on one site who is using http redirection by returning http status code 302. It's common shortage for HTTPURLConnection which didn't put the cookie from response into new access request for the redirect url. 

I search solution from web and find one library jCookie. It's quite old project but it really solve my problem. Here is a sample code to use it's HTTPRedirectHandler to handle redirection case:

    String link = "http://xxx.com/xxx";
    URL url = new java.net.URL(link);

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    connection.setRequestProperty("user-agent","    Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; zh-CN; rv:1.9.1.3)   Gecko/20090824 Firefox/3.5.3");
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");

    StringBuffer sb = new StringBuffer();

    sb.append("xx=x&xx=x");

    OutputStream os = connection.getOutputStream();
    os.write(sb.toString().getBytes("US-ASCII"));
    os.close();

    HTTPRedirectHandler connection1 = new HTTPRedirectHandler(connection);
    connection1.connect();

    connection = connection1.getConnection();

    InputStream in = connection.getInputStream();
    BufferedReader breader = new BufferedReader(new InputStreamReader(in , "UTF8"));
    String str=breader.readLine();

    while(str != null) {
          //Analyse the html;
          str = breader.readLine();
    }

    breader.close();
    connection1.close()

There have one more thing  I did:  update one line in connection function for class HTTPRedirectHandler:

        huc.setFollowRedirects(false);  ->   huc.setInstanceFollowRedirects(false);

Comments:

Post a Comment:
Comments are closed for this entry.

This blog copyright 2009 by leonfan