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

HttpClient_me

2015-08-18 17:41 621 查看
package com.util;

import java.io.BufferedReader;

import java.io.DataInputStream;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.HashMap;

import java.util.Map;

import java.util.Set;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;

import org.apache.commons.httpclient.HttpClient;

import org.apache.commons.httpclient.HttpException;

import org.apache.commons.httpclient.HttpMethod;

import org.apache.commons.httpclient.HttpStatus;

import org.apache.commons.httpclient.NameValuePair;

import org.apache.commons.httpclient.cookie.CookiePolicy;

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

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

import org.apache.commons.httpclient.params.HttpMethodParams;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

public class NetWorkUtil {

private static final Log LOG = LogFactory.getLog(NetWorkUtil.class);

/**
 * Http请求方式
 */
public static enum METHOD {
    POST("POST"), GET("GET");

    private String value;

    private METHOD(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }
}

private static int REQUEST_TIMEOUT = 3 * 1000; // 请求超时
private static int SOCKET_TIMEOUT = 3 * 1000; // 数据接收超时

public void setRequestTimeOut(int time) {
    NetWorkUtil.REQUEST_TIMEOUT = time;
}

public void setSoTimeOut(int time) {
    NetWorkUtil.SOCKET_TIMEOUT = time;
}

public int getRequestTimeOut() {
    return NetWorkUtil.REQUEST_TIMEOUT;
}

public int getSoTimeOut() {
    return NetWorkUtil.SOCKET_TIMEOUT;
}

public static HttpClient getHttpClient() {
    HttpClient client = new HttpClient();
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    client.getParams().setParameter("http.protocol.single-cookie-header",
            true);
    client.getParams().setSoTimeout(SOCKET_TIMEOUT);
    client.getParams().setConnectionManagerTimeout(REQUEST_TIMEOUT);
    return client;
}

private static void setHeaders(HttpMethod method) {
    method.setRequestHeader("Accept",
            "text/html,application/xhtml+xml,application/xml;");
    method.setRequestHeader("Accept-Language", "zh-cn");
    method.setRequestHeader(
            "User-Agent",
            "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3");
    method.setRequestHeader("Accept-Charset", "UTF-8");
    method.setRequestHeader("Keep-Alive", "300");
    method.setRequestHeader("Connection", "Keep-Alive");
    method.setRequestHeader("Cache-Control", "no-cache");
    method.setRequestHeader("Content-Type",
            "application/x-www-form-urlencoded");
}

/**
 * 执行HTTP POST请求,返回请求响应的HTML
 * 
 * @param url
 *            请求的URL地址
 * @param params
 *            请求的查询参数,可以为null
 * @param charset
 *            字符
 * @return 返回请求响应的HTML
 */
public static String doPost(String url, Map params, String charset,
        boolean pretty) {
    StringBuffer response = new StringBuffer();
    HttpClient client = getHttpClient();
    // 创建Post法的实例
    PostMethod method = new PostMethod(url);
    setHeaders(method);
    // 使用系统提供的默认的恢复策略
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler());

    // 设置Http Post数据
    if (params != null) {
        // 填入各个表单域参数
        NameValuePair[] data = null;

        Set sets = params.keySet();
        Object[] arr = sets.toArray();
        int mxsets = sets.size();
        if (mxsets > 0) {
            data = new NameValuePair[mxsets];
        }
        for (int i = 0; i < mxsets; i++) {
            String key = (String) arr[i];
            String val = (String) params.get(key);
            data[i] = new NameValuePair(key, val);
        }
        // 将表单的值放入postMethod
        method.setRequestBody(data);

    }
    try {
        // 执行getMethod
        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(method.getResponseBodyAsStream(),
                            charset));
            String line;
            while ((line = reader.readLine()) != null) {
                if (pretty) {
                    response.append(line).append("\n");
                } else {
                    response.append(line);
                }
            }
            reader.close();
        } else {
            LOG.error("NetWorkUtil post request error status code:"
                    + statusCode);
        }
    } catch (HttpException e) {
        LOG.error("NetWorkUtil HttpException post", e);
    } catch (IOException e) {
        LOG.error("NetWorkUtil IOException post", e);
    } finally {
        method.releaseConnection();
    }
    return response.toString();
}

/**
 * 执行HTTP GET请求,返回请求响应的HTML
 * 
 * @param url
 *            请求的URL地址
 * @param params
 *            请求的查询参,可以为null
 * @param charset
 *            字符
 * @return 返回请求响应的HTML
 */
public static String doGet(String url, Map params, String charset,
        boolean pretty) {
    StringBuffer response = new StringBuffer();
    // 构造HttpClient的实例
    HttpClient client = getHttpClient();
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    client.getParams().setParameter("http.protocol.single-cookie-header",
            true);

    // 创建Get法的实例
    GetMethod method = new GetMethod(url);
    setHeaders(method);
    // 使用系统提供的默认的恢复策略
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler());

    // 设置Http Get数据
    if (params != null) {
        // 填入各个表单域的
        NameValuePair[] data = null;

        Set sets = params.keySet();
        Object[] arr = sets.toArray();
        int mxsets = sets.size();
        if (mxsets > 0) {
            data = new NameValuePair[mxsets];
        }
        for (int i = 0; i < mxsets; i++) {
            String key = (String) arr[i];
            String val = (String) params.get(key);

            data[i] = new NameValuePair(key, val);
        }
        // 将表单的值放入postMethod
        method.setQueryString(data);
    }
    try {
        // 执行getMethod
        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(method.getResponseBodyAsStream(),
                            charset));
            String line;
            while ((line = reader.readLine()) != null) {
                if (pretty) {
                    response.append(line).append("\n");
                } else {
                    response.append(line);
                }
            }
            reader.close();
        } else {
            System.out.println(statusCode);
        }
    } catch (HttpException e) {
        System.out.println("Http错误原因" + e.getMessage());
    } catch (IOException e) {
        System.out.println("IO错误原因" + e.getMessage());
    } finally {
        method.releaseConnection();
    }
    return response.toString();
}

/**
 * 执行HTTP GET请求,返回请求响应的HTML
 * 
 * @param url
 *            请求的URL地址
 * @param params
 *            请求的查询参数,可以为null
 * @param charset
 *            字符
 * @return 返回请求响应的HTML
 */
public static File doGet(String url, Map params, String charset,
        String savePath) {

    File file = null;
    // HttpClient的实
    HttpClient client = getHttpClient();
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    client.getParams().setParameter("http.protocol.single-cookie-header",
            true);

    // 创建Get法的实例
    GetMethod method = new GetMethod(url);
    setHeaders(method);
    // 使用系统提供的默认的恢复策略
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler());

    // 设置Http Get数据
    if (params != null) {
        // 填入各个表单域的
        NameValuePair[] data = null;

        Set sets = params.keySet();
        Object[] arr = sets.toArray();
        int mxsets = sets.size();
        if (mxsets > 0) {
            data = new NameValuePair[mxsets];
        }
        for (int i = 0; i < mxsets; i++) {
            String key = (String) arr[i];
            String val = (String) params.get(key);

            data[i] = new NameValuePair(key, val);
        }
        // 将表单的值放入postMethod
        method.setQueryString(data);
    }
    try {
        // 执行getMethod
        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {

            file = new File(savePath);

            DataInputStream dataInputStream = new DataInputStream(
                    method.getResponseBodyAsStream());
            FileOutputStream fileOutputStream = new FileOutputStream(file);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = dataInputStream.read(buffer)) > 0) {
                fileOutputStream.write(buffer, 0, length);
            }
            dataInputStream.close();
            fileOutputStream.close();

        } else {
            System.out.println(statusCode);
        }
    } catch (HttpException e) {
        System.out.println("Http错误原因" + e.getMessage());
    } catch (IOException e) {
        System.out.println("IO错误原因" + e.getMessage());
    } finally {
        method.releaseConnection();
    }
    return file;
}

public static void main(String[] args) {
    String url = "http://youxi.baidu.com/seven_cool_game.xhtml";
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("c", "getAvailableId");
    String charset = "UTF-8";
    String response = doPost(url, params, charset, true);

    System.out.println(response);
}


}

需要的jar包:http://pan.baidu.com/s/1i3haYxf
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: