httpClient_3.x版用法

/**
 * 
 */
package me;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang3.StringUtils;

/**
 * Created by lzd on 2016年6月27日 上午9:47:36  
 */
public class HttpClient_3x {

    public static void main(String[] args) throws Exception{
//        req();
//        isRedirect();
        loginReq();
    }
    
    //post or get request 
    public static void req() throws Exception{
        HttpClient httpClient = new HttpClient();
        
//        配置代理
//        httpClient.getHostConfiguration().setProxy("127.0.0.1", 80);
        
//        PostMethod postMethod = new PostMethod("http://java.sun.com");
        
        GetMethod getMethod = new GetMethod("http://java.sun.com");
        
        int executeStatus = httpClient.executeMethod(getMethod);
        System.out.println(executeStatus);//成功返回200,应该是响应的状态码
        
//        打印返回的信息
        String responseBodyAsString = getMethod.getResponseBodyAsString();
        System.out.println(responseBodyAsString);

//        释放连接
        getMethod.releaseConnection();
        
    }
    
    //get or post append params
    
    private static GetMethod getGetMethod(){
        return new GetMethod("www.aa.com/a?key = 123");
    }
    
    private static PostMethod getPostMethod(){
    
        PostMethod postMethod = new PostMethod("www.aa.com/a");
        NameValuePair nameValuePair = new NameValuePair("key", "val");
        postMethod.setRequestBody(new NameValuePair[]{nameValuePair});
        return postMethod;
    }
    
//    检测是否重定向
//    301 SC_MOVED_PERMANENTLY 页面已经永久移到另外一个新地址
//    302 SC_MOVED_TEMPORARILY 页面暂时移动到另外一个新的地址
//    303 SC_SEE_OTHER 客户端请求的地址必须通过另外的 URL 来访问
//    307 SC_TEMPORARY_REDIRECT 同 SC_MOVED_TEMPORARILY
    
    public static void isRedirect() throws Exception{
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod("http://192.168.10.150/pdc/app/book/info/index.html");
        httpClient.executeMethod(getMethod);
        
        getMethod.releaseConnection();
        
        int statusCode = getMethod.getStatusCode();
        
        if(statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY
                || statusCode == HttpStatus.SC_SEE_OTHER 
                || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT){
            Header responseHeader = getMethod.getResponseHeader("location");
            if(responseHeader != null){
                String value = responseHeader.getValue();
                
                if(StringUtils.isNotEmpty(value)){
                    GetMethod method = new GetMethod(value);
                    httpClient.executeMethod(method);
                    //执行之后的操作
                }
            }
        }
    }
    
    /*
     * 模拟登录
     * 首先访问正常页面
     * 拿到返回的结果,判断是否让登录,如果让登录,就登录后再进。
     * 
     * 
     */
    public static void loginReq() throws Exception{
        String targetUrl = "/pdc/app/book/info/index.html";
        
        HttpClient httpClient = new HttpClient();
        httpClient.getHostConfiguration().setHost("192.168.10.150", 80);
        PostMethod postMethod = new PostMethod(targetUrl);
        httpClient.executeMethod(postMethod);
        postMethod.releaseConnection();
        
        int statusCode = postMethod.getStatusCode();
        
        if(statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                || statusCode == HttpStatus.SC_MOVED_TEMPORARILY
                || statusCode == HttpStatus.SC_SEE_OTHER
                || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT){
            Header responseHeader = postMethod.getResponseHeader("location");
            
            if (responseHeader != null){
                String value = responseHeader.getValue();
                System.out.println("redirect location = "+value);
                if(StringUtils.isNotEmpty(value) && value.indexOf("login") != -1){
                    NameValuePair name = new NameValuePair("userName","admin");
                    NameValuePair pwd = new NameValuePair("pwd","admin");
                    
                    PostMethod loginMethod = new PostMethod("/pdc/userLogin.html");
                    loginMethod.setRequestBody(new NameValuePair[]{name,pwd});
                    
                    httpClient.executeMethod(loginMethod);
                    loginMethod.releaseConnection();
                    

                    /**  得到cookie的方法 
                    Cookie[] cookies = httpClient.getState().getCookies();
                    System.out.println("----------------------------cookie start ------------------------------------------");
                    for (Cookie cookie : cookies) {
                        System.out.println(cookie);
                    }
                    System.out.println("----------------------------------------------------------------------");
                    Header[] headerCookies = postMethod.getResponseHeaders("Set-cookie");
                    for (Header header : headerCookies) {
                        System.out.println(header);
                    }
                    System.out.println("----------------------------cookie end------------------------------------------");
                     */
                    
                    GetMethod tarGetMethod = new GetMethod(targetUrl);
                    httpClient.executeMethod(tarGetMethod);
                    System.out.println(tarGetMethod.getResponseBodyAsString());
                    tarGetMethod.releaseConnection();
                }
            } else {
                System.out.println("invalid redirect");
            }
        } else {
            System.out.println(postMethod.getResponseBodyAsString());
        }
    }
    
    //多线程下访问httpclient(同一个站点),只需要在实例化httpclient时传入MultiThreadedHttpConnectionManager即可
    public static void getHttpClient(){
        MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
        
        HttpClient client = new HttpClient(connectionManager);
    }
    
}

//通过http上传文件、提交xml格式数据的例子请看原文地址
//http://www.blogjava.net/Alpha/archive/2007/01/22/95216.html
posted @ 2016-06-27 12:06  姩澕  阅读(499)  评论(0编辑  收藏  举报