对HttpClient的一些封装方法

摘自项目中的util,利用httpclient发送get、post请求,上传、下载文件,可以直接拿去当作util类来使用。

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.io.IOUtils;
import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 * HttpClient 封装
 * Created by Administrator on 2016/12/7.
 */
public class SimpleHttpClient {

    public static final Logger logger = LoggerFactory.getLogger(SimpleHttpClient.class);

    public static final Integer cache_size = 4096;

    public static InputStream invokePost4Stream(String url, Map<String, Object> params, Map<String, String> headers,int timeout) throws IOException {
        HttpClient hc = new HttpClient();
        PostMethod post = new PostMethod(url);
        if (headers != null) {
            Set<Map.Entry<String, String>> entrys = headers.entrySet();
            for (Map.Entry<String, String> entry : entrys) {
                post.addRequestHeader(entry.getKey(),String.valueOf(entry.getValue()));
            }
        }
        post.getParams().setContentCharset("UTF-8");
        if (params != null) {
            Set<Map.Entry<String, Object>> entrys = params.entrySet();
            for (Map.Entry<String, Object> entry : entrys) {
                post.addParameter(entry.getKey(),String.valueOf(entry.getValue()));
            }
        }
        try {
            hc.getParams().setSoTimeout(timeout);
            hc.executeMethod(post);
            return post.getResponseBodyAsStream();
        } finally {
//            post.releaseConnection();
        }
    }

    public static HttpResponse httpGetHttpResponse(String url) throws IOException {
        String uuid = UUID.randomUUID().toString();
        logger.info("http get request  uuid={},url={}", uuid, url);
        //get请求返回结果
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(url);
        try {
            HttpResponse response = client.execute(request);
            return response;
        } catch (IOException e) {
            throw e;
        } finally {
            request.releaseConnection();
            CloseUtil.close(client);
        }
    }

    public static JSONObject invokePost(String urlString, JSONObject json) throws IOException {
        // Configure and open a connection to the site you will send the request
        URL url = new URL(urlString);
        URLConnection urlConnection = url.openConnection();
        // 设置doOutput属性为true表示将使用此urlConnection写入数据
        urlConnection.setDoOutput(true);
        // 定义待写入数据的内容类型,我们设置为application/x-www-form-urlencoded类型
        urlConnection.setRequestProperty("content-type", "application/json");
        // 得到请求的输出流对象
        OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
        // 把数据写入请求的Body
        out.write(json.toJSONString());
        out.flush();
        out.close();
        // 从服务器读取响应
        InputStream inputStream = urlConnection.getInputStream();
        String encoding = urlConnection.getContentEncoding();
        String body = IOUtils.toString(inputStream, encoding);
        JSONObject result = JSONObject.parseObject(body);
        return result;
    }

    public static JSONObject invokePost(String urlString, JSONObject json, Map<String, String> headers) throws IOException {

        // Configure and open a connection to the site you will send the request
        URL url = new URL(urlString);
        URLConnection urlConnection = url.openConnection();
        // 设置doOutput属性为true表示将使用此urlConnection写入数据
        urlConnection.setDoOutput(true);
        // 定义待写入数据的内容类型,我们设置为application/x-www-form-urlencoded类型
        urlConnection.setRequestProperty("content-type", "application/json");
        if(headers != null){
            Set<Map.Entry<String, String>> entrys = headers.entrySet();
            for (Map.Entry<String, String> entry : entrys) {
                urlConnection.setRequestProperty(entry.getKey(),String.valueOf(entry.getValue()));
            }
        }
        // 得到请求的输出流对象
        OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
        // 把数据写入请求的Body
        out.write(json.toJSONString());
        out.flush();
        out.close();
        // 从服务器读取响应
        InputStream inputStream = urlConnection.getInputStream();
        String encoding = urlConnection.getContentEncoding();
        String body = IOUtils.toString(inputStream, encoding);
        JSONObject result = JSONObject.parseObject(body);
        return result;
    }


    public static InputStream httpGet4Stream(String url) throws IOException {
        return httpGet4Stream(url, null);
    }

    public static InputStream httpGet4Stream(String url, Map<String, String> headers) throws IOException {
        String uuid = UUID.randomUUID().toString();
        logger.info("http get request  uuid={},url={}", uuid, url);
        //get请求返回结果
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(url);
        try {
            if (headers != null) {
                Set<Map.Entry<String, String>> entrys = headers.entrySet();
                for (Map.Entry<String, String> entry : entrys) {
                    request.setHeader(entry.getKey(), String.valueOf(entry.getValue()));
                }
            }
            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();
            return entity.getContent();
        } catch (IOException e) {
            throw e;
        } finally {
            request.releaseConnection();
            CloseUtil.close(client);
        }
    }


    /**
     * 下载文件
     *
     * @param url
     * @param bao
     * @return
     * @throws IOException
     */
    public static String httpGetFile(String url, ByteArrayOutputStream bao) throws IOException {
        String fileName = null;
        String uuid = UUID.randomUUID().toString();
        logger.info("http get request  uuid={},url={}", uuid, url);
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(url);
        try {
            HttpResponse response = client.execute(request);
            /**请求发送成功,并得到响应**/
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                InputStream in = entity.getContent();
                long length = entity.getContentLength();
                if (length <= 0) {
                    logger.error("下载文件不存在!");
                    return fileName;
                }
                byte[] buffer = new byte[cache_size];
                int readLength;
                while ((readLength = in.read(buffer)) > 0) {
                    byte[] bytes = new byte[readLength];
                    System.arraycopy(buffer, 0, bytes, 0, readLength);
                    bao.write(bytes);
                }
                bao.flush();
                fileName = getFileName(response);
            }
            return fileName;
        } catch (IOException e) {
            throw e;
        } finally {
            request.releaseConnection();
            CloseUtil.close(client);
        }
    }


    public static HttpResponse httpPostHttpResponse(String url, JSONObject jsonParam) throws IOException {
        String uuid = UUID.randomUUID().toString();
        logger.info("http post request  uuid={},url={},param={}", uuid, url, jsonParam);
        //post请求返回结果
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpPost request = new HttpPost(url);
        try {
            checkJsonParam(jsonParam, request);
            HttpResponse response = client.execute(request);
            return response;
        } catch (IOException e) {
            throw e;
        } finally {
            request.releaseConnection();
            CloseUtil.close(client);
        }
    }

    private static void checkJsonParam(JSONObject jsonParam, HttpPost method) {
        if (null != jsonParam) {
            //解决中文乱码问题
            StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            method.setEntity(entity);
        }
    }

    /**
     * post请求
     *
     * @param url
     * @param jsonParam
     * @param timeout
     * @return
     * @throws IOException
     */
    public static JSONObject httpPost(String url, JSONObject jsonParam, Integer timeout) throws IOException {
        String uuid = UUID.randomUUID().toString();
        logger.info("http post request  uuid={},url={},param={}", uuid, url, jsonParam);
        //post请求返回结果
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        JSONObject jsonResult = null;
        HttpPost request = new HttpPost(url);
        try {
            if (timeout != null && timeout > 0) {
                RequestConfig requestConfig = RequestConfig.custom()
                        .setConnectionRequestTimeout(timeout)
                        .setConnectTimeout(timeout)
                        .setSocketTimeout(timeout).build();
                request.setConfig(requestConfig);
            }
            checkJsonParam(jsonParam, request);
            HttpResponse result = httpClient.execute(request);
            /**请求发送成功,并得到响应**/
            if (result.getStatusLine().getStatusCode() == 200) {
                /**读取服务器返回过来的json字符串数据**/
                String str = EntityUtils.toString(result.getEntity());
                /**把json字符串转换成json对象**/
                jsonResult = JSONObject.parseObject(str);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            request.releaseConnection();
            CloseUtil.close(httpClient);
        }
        logger.info("http post response uuid={},response={}", uuid, jsonResult);
        return jsonResult;
    }

    /**
     * post请求
     *
     * @param url
     * @param jsonParam
     * @return
     * @throws IOException
     */
    public static JSONObject httpPost(String url, JSONObject jsonParam) throws IOException {
        return httpPost(url, jsonParam, null);
    }

    /**
     * 上传文件
     *
     * @param url
     * @param file
     * @return
     * @throws IOException
     */
    public static JSONObject httpPost(String url, File file) throws IOException {
        String uuid = UUID.randomUUID().toString();
        logger.info("http post request  uuid={},url={},file={}", uuid, url, file);
        //post请求返回结果
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        JSONObject jsonResult = null;
        HttpPost request = new HttpPost(url);
        try {
            if (null != file) {
                FileBody binFileBody = new FileBody(file);
                MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
                multipartEntityBuilder.addPart(file.getName(), binFileBody);
                // 设置上传的其他参数
//                setUploadParams(multipartEntityBuilder, params);
                HttpEntity reqEntity = multipartEntityBuilder.build();
                request.setEntity(reqEntity);
            }
            HttpResponse result = httpClient.execute(request);
            /**请求发送成功,并得到响应**/
            if (result.getStatusLine().getStatusCode() == 200) {
                /**读取服务器返回过来的json字符串数据**/
                String str = EntityUtils.toString(result.getEntity());
                /**把json字符串转换成json对象**/
                jsonResult = JSONObject.parseObject(str);
            }
        } catch (IOException e) {
            httpClient.close();
            throw e;
        } finally {
            request.releaseConnection();
            CloseUtil.close(httpClient);
        }
        logger.info("http post response uuid={},response={}", uuid, jsonResult);
        return jsonResult;
    }

    /**
     * 发送get请求
     *
     * @param url 路径
     * @return
     */
    public static JSONObject httpGet(String url) throws IOException {
        String uuid = UUID.randomUUID().toString();
        logger.info("http get request  uuid={},url={}", uuid, url);
        //get请求返回结果
        JSONObject jsonResult = null;
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(url);
        try {
            HttpResponse response = client.execute(request);
            /**请求发送成功,并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                logger.debug("response : " + response);
                /**读取服务器返回过来的json字符串数据**/
                String strResult = EntityUtils.toString(response.getEntity());
                /**把json字符串转换成json对象**/
                jsonResult = JSONObject.parseObject(strResult);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            request.releaseConnection();
            CloseUtil.close(client);
        }
        logger.info("http get response uuid={},response={}", uuid, jsonResult);
        return jsonResult;
    }

    private static String getFileName(HttpResponse response) {
        Header contentHeader = response.getFirstHeader("Content-Disposition");
        String filename = null;
        if (contentHeader != null) {
            HeaderElement[] values = contentHeader.getElements();
            if (values.length == 1) {
                NameValuePair param = values[0].getParameterByName("filename");
                if (param != null) {
                    try {
                        filename = new String(param.getValue().toString().getBytes(), "utf-8");
                        filename = URLDecoder.decode(param.getValue(), "utf-8");
                        filename = param.getValue();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return filename;
    }

}

猜你喜欢

转载自blog.csdn.net/innerpeaceScorpio/article/details/70568883
今日推荐