您的位置:首页 > 理论基础 > 计算机网络

commons-httpclient.jar的使用(处理页面重定向)

2008-03-20 15:31 519 查看
 


package com.test;




import java.io.IOException;




import org.apache.commons.httpclient.Header;


import org.apache.commons.httpclient.HttpClient;


import org.apache.commons.httpclient.HttpMethod;


import org.apache.commons.httpclient.HttpStatus;


import org.apache.commons.httpclient.StatusLine;


import org.apache.commons.httpclient.methods.GetMethod;






public class RedirectTest ...{


    




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


        


        HttpClient client = new HttpClient();


        


        client.getHostConfiguration();


    //    client.getHostConfiguration().setHost("www.imobile.com.cn", 80, "http");


    //    client.getHostConfiguration().setHost("", 80);


        


        HttpMethod method = new GetMethod("http://127.0.0.1:8080/httpClient/a.jsp");


        client.executeMethod(method);


        StatusLine statusMsg = method.getStatusLine();


        System.out.println(statusMsg);


        System.out.println(method.getResponseBodyAsString());


        System.out.println("--------------------------------------------------------------------------");


        


        


        //检查是否有重定向


        int statusCode = method.getStatusCode();


        System.out.println(statusCode);


        if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY 




                || statusCode ==  HttpStatus.SC_SEE_OTHER || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)...{


            //读取新的URL地址


            Header header = method.getRequestHeader("location");




            if (header != null)...{


                String newurl = header.getValue();




                if (header == null || header.equals(""))...{


                    newurl = "/";


                }


                GetMethod redirect = new GetMethod(newurl);


                client.executeMethod(redirect);


                System.out.println("redirect:  " + redirect.getStatusLine().toString());


                redirect.releaseConnection();




            }else...{


                System.out.println("Invialid Redirect///");


            }


        }


        


    }


}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息