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

 

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///");
            }

        }

        
    }

}

你可能感兴趣的:(jar包的使用)