spring 中 HttpClientUtil工具类编写

  1. CloseableHttpClient类
package com.phfund.micro.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.phfund.micro.dto.AuthorizedVo;
import com.phfund.micro.dto.ResponseWrapper;
import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClientUtil {

    // json对象
    private static ObjectMapper mapper = new ObjectMapper();
    /**
     * 发送post请求,json格式数据
     * @param url
     * @param params
     * @return
     */
    public static ResponseWrapper postJsonData(String url, AuthorizedVo authorizedVo){
        CloseableHttpClient httpclient = HttpClientUtil.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-type","application/json; charset=utf-8");
        //拼接参数
        JSONObject jsonParams = new JSONObject();
        jsonParams.put("indexcode", authorizedVo.getIndexcode());
        jsonParams.put("param", authorizedVo.getParam());
        jsonParams.put("consumerMark", authorizedVo.getConsumerMark());
        jsonParams.put("token", authorizedVo.getToken());
        jsonParams.put("consumerName", authorizedVo.getConsumerName());
        jsonParams.put("page", authorizedVo.getPage());
        jsonParams.put("rows", authorizedVo.getRows());

        //配置请求超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(1*60*1000)                //设置连接超时时间,单位毫秒
                .setSocketTimeout(3*60*1000).build();        //请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
        httpPost.setConfig(requestConfig);

        CloseableHttpResponse response=null;
        try {
            httpPost.setEntity(new StringEntity(jsonParams.toString(), Charset.forName("UTF-8")));
            response = httpclient.execute(httpPost);//response.close()会被自动调用
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        /**请求发送成功,并得到响应**/
        ResponseWrapper responseWrapper=null;
        if(response != null){
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                HttpEntity httpEntity = response.getEntity();
                String result=null;
                try {
                    result = EntityUtils.toString(httpEntity);
                } catch (ParseException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 返回ResponseWrapper:
                try {
                    responseWrapper= mapper.readValue(result, ResponseWrapper.class);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return responseWrapper;
    }

    /**
     * 发送post请求
     * @param url
     * @param params
     * @return
     */
    public static JSONObject postData(String url,AuthorizedVo authorizedVo){
        CloseableHttpClient httpclient = HttpClientUtil.createDefault();
        HttpPost httpPost = new HttpPost(url);

        //拼接参数
        List list = new ArrayList();

        NameValuePair pair1 = new BasicNameValuePair("indexcode", authorizedVo.getIndexcode());
        NameValuePair pair2 = new BasicNameValuePair("consumerMark", authorizedVo.getConsumerMark());

        list.add(pair1);
        list.add(pair2);
        CloseableHttpResponse response=null;
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));
            response = httpclient.execute(httpPost);
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        /**请求发送成功,并得到响应**/
        JSONObject jsonObject=null;
        if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            HttpEntity httpEntity = response.getEntity();
            String result=null;
            try {
                result = EntityUtils.toString(httpEntity);
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 返回json格式:
            jsonObject = JSONObject.fromObject(result);
        }
        return jsonObject;
    }

    /**
     * 向指定URL发送GET方法的请求
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * get请求
     * @param url
     * @param param  请求参数
     * @return
     */
    public static JSONObject httpGet(String url, String param){
        JSONObject jsonResult = null;   //get请求返回结果
        try {

            CloseableHttpClient httpclient = HttpClientUtil.createDefault();
            //发送get请求
            HttpGet request = new HttpGet(url);
            URI realUrl = new URI(url + "?" + param);
            request.setURI(realUrl);
            HttpResponse response = httpclient.execute(request);

            /**请求发送成功,并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                /**读取服务器返回过来的json字符串数据**/
                String strResult = EntityUtils.toString(response.getEntity());

                /**把json字符串转换成json对象**/
                jsonResult = JSONObject.fromObject(strResult);
                url = URLDecoder.decode(url, "UTF-8");
            } else {
                System.out.println("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return jsonResult;
    }

    public static CloseableHttpClient createDefault() {
        return HttpClientBuilder.create().build();
    }

}

你可能感兴趣的:(spring 中 HttpClientUtil工具类编写)