Http调用接口工具类————HttpClientUtil

一. Http调用接口工具类

1.pom 依赖

<dependency>
    <groupId>commons-httpclientgroupId>
    <artifactId>commons-httpclientartifactId>
    <version>3.1version>
dependency>

2.工具类

package com.hzcominfo.application.catalogv2.common.util;

import com.hzcominfo.application.catalogv2.web.rdto.util.ResponseDto;
import com.hzcominfo.application.common.util.JsonUtils;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 封装http方法
 * 
 * @author wzb
 *
 */
public class HttpClientUtil {

    // 本地异常日志记录对象
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 执行post方法
     * 
     * @param url
     * @param params
     * @return
     */
    public static ResponseDto doPost(String url, Map<String, Object> params) {
        ResponseDto responseDto = new ResponseDto();
        try {
            HttpClient client = new HttpClient();
            PostMethod post = new PostMethod(url);

            int count = 0;
            NameValuePair[] nameValuePairs = new NameValuePair[params.size()];
            for (String key : params.keySet()) {
                String value = params.get(key) == null ? "" : params.get(key).toString();
                NameValuePair param = new NameValuePair(key, value);
                nameValuePairs[count] = param;
                count++;
            }
            post.setRequestBody(nameValuePairs);

            client.executeMethod(post);
            String respStr = post.getResponseBodyAsString();
            responseDto = JsonUtils.parse(respStr, ResponseDto.class);
            post.releaseConnection();
            return responseDto;
        } catch (Exception e1) {
            e1.printStackTrace();
            responseDto.setErrcode("0");
            responseDto.setErrmsg("post方法,远程调用时出错!");
            return responseDto;
        }
    }

    /**
     * 执行post方法
     * 
     * @param url
     * @param params
     * @return
     */
    public static String doPost1(String url, Map<String, Object> params) {
        ResponseDto responseDto = new ResponseDto();
        try {
            HttpClient client = new HttpClient();
            PostMethod post = new PostMethod(url);
            post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            int count = 0;
            NameValuePair[] nameValuePairs = new NameValuePair[params.size()];
            for (String key : params.keySet()) {
                String value = params.get(key) == null ? "" : params.get(key).toString();
                NameValuePair param = new NameValuePair(key, value);
                nameValuePairs[count] = param;
                count++;
            }
            post.setRequestBody(nameValuePairs);
            client.executeMethod(post);
            String respStr =  new String(post.getResponseBody(), StandardCharsets.UTF_8);
            post.releaseConnection();
            return respStr;
        } catch (Exception e1) {
            e1.printStackTrace();
            responseDto.setErrcode("0");
            responseDto.setErrmsg("post方法,远程调用时出错!");
            return responseDto.toString();
        }
    }

    /**
     * 执行post方法
     * 
     * @param url
     * @param params
     * @return
     */
    public static void doResponsePost(String url, Map<String, Object> params, HttpServletResponse response) {
        InputStream is = null;
        OutputStream os = null;
        HttpClient client = new HttpClient();
        try {
            PostMethod post = new PostMethod(url);
            int count = 0;
            NameValuePair[] nameValuePairs = new NameValuePair[params.size()];
            for (String key : params.keySet()) {
                String value = params.get(key) == null ? "" : params.get(key).toString();
                NameValuePair param = new NameValuePair(key, value);
                nameValuePairs[count] = param;
                count++;
            }
            post.setRequestBody(nameValuePairs);
            client.executeMethod(post);
            byte[] respStr = post.getResponseBody();
            is = new ByteArrayInputStream(respStr);
            os = response.getOutputStream();
            byte[] buffer = new byte[1024 * 1024];
            while ((count = is.read(buffer)) != -1) {
                os.write(buffer, 0, count);
                os.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (os != null) {
                    os.close();
                }
                response.flushBuffer();
            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }
    }

    /**
     * 执行下载附件方法
     * 
     * @param url
     * @param params
     * @return
     */
    public static void doAppDownLoadPost(String url, Map<String, Object> params, HttpServletResponse response) {
        InputStream is = null;
        OutputStream os = null;
        HttpClient client = new HttpClient();
        try {
            PostMethod post = new PostMethod(url);
            int count = 0;
            NameValuePair[] nameValuePairs = new NameValuePair[params.size()];
            for (String key : params.keySet()) {
                String value = params.get(key) == null ? "" : params.get(key).toString();
                NameValuePair param = new NameValuePair(key, value);
                nameValuePairs[count] = param;
                count++;
            }
            post.setRequestBody(nameValuePairs);

            client.executeMethod(post);
            byte[] respStr = post.getResponseBody();

            Header fileName = post.getResponseHeader("fileName");// 文件名称
            is = new ByteArrayInputStream(respStr);
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName.getValue());
            os = response.getOutputStream();
            byte[] buffer = new byte[1024 * 1024];
            while ((count = is.read(buffer)) != -1) {
                os.write(buffer, 0, count);
                os.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (os != null) {
                    os.close();
                }
                response.flushBuffer();
            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }
    }

    /**
     * 执行post方法
     *
     * @param url
     * @param params
     * @return
     */
    public static String doPost3(String url, Map<String, Object> params, HttpServletRequest request) {
        ResponseDto responseDto = new ResponseDto();
        try {
            HttpClient client = new HttpClient();
            PostMethod post = new PostMethod(url);
            post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            post.addRequestHeader("Cookie",request.getHeader("Cookie"));
            int count = 0;
            NameValuePair[] nameValuePairs = new NameValuePair[params.size()];
            for (String key : params.keySet()) {
                String value = params.get(key) == null ? "" : params.get(key).toString();
                NameValuePair param = new NameValuePair(key, value);
                nameValuePairs[count] = param;
                count++;
            }
            post.setRequestBody(nameValuePairs);
            client.executeMethod(post);
            String respStr =  new String(post.getResponseBody(), StandardCharsets.UTF_8);
            post.releaseConnection();
            return respStr;
        } catch (Exception e1) {
            e1.printStackTrace();
            responseDto.setErrcode("0");
            responseDto.setErrmsg("post方法,远程调用时出错!");
            return responseDto.toString();
        }
    }

	/**
     * 执行get方法
     *
     * @param url
     * @param params
     * @return
     */
    public String doGet(String url, Map<String, Object> params) {
        ResponseDto responseDto = new ResponseDto();
        try {
            HttpClient client = new HttpClient();
            GetMethod get = new GetMethod(url);

            int count = 0;
            NameValuePair[] nameValuePairs = new NameValuePair[params == null ? 0 : params.size()];
            if (params != null) {
                for (String key : params.keySet()) {
                    String value = params.get(key) == null ? "" : params.get(key).toString();
                    NameValuePair param = new NameValuePair(key, value);
                    nameValuePairs[count] = param;
                    count++;
                }
            }
            get.setQueryString(nameValuePairs);
            client.executeMethod(get);
            String respStr = new String(get.getResponseBody(), StandardCharsets.UTF_8);
            get.releaseConnection();
            return respStr;
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            responseDto.setErrcode(AttrConstants.ERROR_CODE);
            responseDto.setErrmsg(e.getMessage());
            return responseDto.toString();
        }
    }

}

你可能感兴趣的:(Java)