HttpClientUtils 工具类

maven项目需要在pom文件中添加相关的包依赖 

 <dependency>
            <groupId>top.jfunc.json</groupId>
            <artifactId>Json-Gson</artifactId>
            <version>1.0</version>
 </dependency>

package com.laixh.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.google.gson.Gson;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;


/**
 * HttpClientUtils 工具类
 */
public class HttpClientUtils {
    private static Logger logger = org.apache.log4j.Logger.getLogger(HttpClientUtils.class.getSimpleName());
    public static final String UTF8 = "UTF-8";
    public static final String GBK = "GBK";
    private final static String CONTENT_TYPE_TEXT_JSON = "text/json";

    public static String get(String url, String charset) {
        CloseableHttpClient httpClient = HttpClients.custom().build();
        HttpGet httpGet = new HttpGet(url);
        String result = null;
        try {
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                result = EntityUtils.toString(entity, charset);
            }
            EntityUtils.consume(entity);
        } catch (Exception e) {
            logger.error(url, e);
        } finally {
            IOUtils.closeQuietly(httpClient);
        }

        return result;
    }


    public static String get(String url, Map<String, String> headers, Map<String, String> data, String charset) {
        StringBuilder para = new StringBuilder();
        for (String item : data.keySet()) {
            para.append("&");
            para.append(item);
            para.append("=");
            para.append(URLEncoder.encode(data.get(item)));
        }

        if (para.length() > 0) {
            url = url.indexOf("?") > 0 ? url + para : url + "?" + para.substring(1);
        }
        return get(url, headers, charset);
    }


    public static String get(String url, Map<String, String> headers, String charset) {
        CloseableHttpClient httpClient = HttpClients.custom().build();
        HttpGet httpGet = new HttpGet(url);
        String result = null;
        try {
            if (headers != null) {
                for (String item : headers.keySet()) {
                    httpGet.addHeader(item, headers.get(item));
                }
            }
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                result = EntityUtils.toString(entity, charset);
            }
            EntityUtils.consume(entity);
        } catch (Exception e) {
            logger.error(url, e);
        } finally {
            IOUtils.closeQuietly(httpClient);
        }
        return result;
    }


    public static String post(String url, Map map, String charset) {
        return request(url, "post", null, map, charset);
    }


    public static String post(String url, Map<String, String> header, Map map, String charset) {
        return request(url, "post", header, map, charset);
    }

    public static String put(String url, Map<String, String> header, Map map, String charset) {
        return request(url, "put", header, map, charset);
    }

    public static String request(String url, String method, Map<String, String> header, Map map, String charset) {
        CloseableHttpClient httpClient = null;
        httpClient = HttpClients.custom().build();

        HttpEntityEnclosingRequestBase hp = null;
        String result = null;
        if ("put".equals(method)) {
            hp = new HttpPut(url);
        } else {
            hp = new HttpPost(url);

        }
        if (header != null) {
            for (String item : header.keySet()) {
                hp.addHeader(item, header.get(item));
            }
        }

        try {
            if (map != null && map.size() > 0) {
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                Set keys = map.keySet();
                for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
                    String name = ObjectUtils.toString(iterator.next());
                    String value =ObjectUtils.toString(map.get(name));
                    params.add(new BasicNameValuePair(name, value));
                }
                hp.setEntity(new UrlEncodedFormEntity(params, charset));
            }

            HttpResponse response = httpClient.execute(hp);
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                result = EntityUtils.toString(entity, charset);
            }
            EntityUtils.consume(entity);
        } catch (Exception e) {
            logger.error(url, e);
        } finally {
            IOUtils.closeQuietly(httpClient);
        }
        return result;
    }

    public static String postContent(String url, Map map, String charset) {
        CloseableHttpClient httpclient = null;
        String ret = null;
        httpclient = HttpClients.custom().build();

        HttpPost httppost = new HttpPost(url);
        if (map != null && map.size() > 0) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            Set keys = map.keySet();
            for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
                String name = (String) iterator.next();
                String value = (String) map.get(name);
                params.add(new BasicNameValuePair(name, value));
            }
            try {
                httppost.setEntity(new UrlEncodedFormEntity(params, charset));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        try {
            CloseableHttpResponse response = null;
            response = httpclient.execute(httppost);
            if (null != response) {
                HttpEntity entity = null;
                try {
                    entity = response.getEntity();
                    if (entity != null) {
                        ret = new String(IOUtils.toByteArray(entity.getContent()), getResCharset(response, charset));
                        logger.debug("解析后的数据: " + ret);
                    }
                    EntityUtils.consume(entity);
                } finally {
                    response.close();
                }
            }

        } catch (Exception e) {
            logger.error(url, e);
        } finally {
            IOUtils.closeQuietly(httpclient);
        }
        return ret;
    }

    public static String postContent(String url, String content, String charset) {
        String responseContent = "";
        CloseableHttpClient httpclient = HttpClients.custom().build();;

        HttpPost httppost = new HttpPost(url);
        HttpEntity postEntity = new StringEntity(content, charset);
        httppost.setEntity(postEntity);
        System.out.println("executing request" + httppost.getRequestLine());
        try {

            CloseableHttpResponse response = null;
            try {
                response = httpclient.execute(httppost);
            } catch (Exception e) {
                return "";
            }
            if (null != response) {
                try {
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        try {
                            responseContent = new String(IOUtils.toByteArray(entity.getContent()), getResCharset(response, charset));
                            logger.debug( responseContent);
                        } catch (Exception ee) {
                            logger.error(ee.getMessage());
                        }
                    }
                    EntityUtils.consume(entity);
                } finally {
                    response.close();
                }
            }

        } catch (Exception e) {
            logger.debug(e);
        }
        return responseContent;
    }

    public static String getResCharset(CloseableHttpResponse response, String charset) {
        Header[] contentTypes = response.getHeaders("Content-Type");
        String resCharset = charset;
        int totalTypes = null != contentTypes ? contentTypes.length : 0;
        for (int i = 0; i < totalTypes; i++) {
            String[] value = contentTypes[i].getValue().toLowerCase().split(";");
            for (int j = 0; j < value.length; j++) {
                if (value[j].startsWith("charset=")) {
                    resCharset = value[j].substring("charset=".length());
                }
            }

        }
        return resCharset;
    }

    /**
     * 参数 json格式
     * @param url
     * @param param
     * @return
     */
    public static String postJsonRequest(String url, Map<String, Object> param)   {

        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";
        try {
            try {
                HttpPost httpPost = new HttpPost(url);
                httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
                Gson gson = new Gson();
                String parameter = gson.toJson(param);
                StringEntity se = new StringEntity(parameter);
                se.setContentType(CONTENT_TYPE_TEXT_JSON);
                httpPost.setEntity(se);
                response = client.execute(httpPost);
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity, "UTF-8");
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                response.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
    public static void main(String[] args) {
        Map<String, Object> jsonObject = new HashMap<>();
        Map<String, Object> extras = new HashMap<>();
        jsonObject.put("title", "title");
        //jsonObject.put("noticeTitle",noticeTitle);
        jsonObject.put("shareRange","2");
        jsonObject.put("createTime","20180101");
        jsonObject.put("openType","3");
        jsonObject.put("jumpUrl","");
        //jsonObject.put("batchToUsers",batchToUsers);
        jsonObject.put("coverImgUrl","");
        jsonObject.put("summary","");
        extras.put("aa","er3");
        extras.put("bb","rqoutq");
        Gson gson = new Gson();
        String extrasJson = gson.toJson(extras);
        jsonObject.put("extras",extrasJson);
        jsonObject.put("mc_widget_identifier","");
        String urlN = "https://amobiletest.anta.com/mpm-api/api/tempmsg/create_temp_msg_and_push?appKey=55551f01&sourceType=todo&touser=2018019633&accessToken=aa584534-1e7c-47bf-b02d-7db853ff2630";
        System.out.println(postJsonRequest(urlN,jsonObject));
    }

}

package app.ext.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Slf4j
public class HttpClientMainExt {

    private final static Logger logger = LoggerFactory.getLogger(HttpClientMainExt.class);

    public static JSONObject httpPostJson(String url, Map<String, Object> params, Map<String, String> headers)
            throws Exception {
        // post请求返回结果
        logger.info("url:{},params:{},headers:{}",url,JSON.toJSONString(params),JSON.toJSONString(headers));
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost method = new HttpPost(url);
        setPostHead(method, headers);
        JSONObject jsonObject = new JSONObject();
        try {
            String str = "";

            if (params == null) {
                params = new HashMap<String, Object>();
            }
            if (null != params) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(JSON.toJSONString(params), "utf-8");// JSON请求字符串
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json; charset=utf-8");
                method.setEntity(entity);
            }
            HttpResponse result = httpclient.execute(method);
            /** 读取服务器返回过来的json字符串数据 **/
            str = getRespString(result.getEntity());
            jsonObject = JSONObject.parseObject(str);
            logger.info("返回结果result:{}",url,JSON.toJSONString(params),JSON.toJSONString(headers),jsonObject);
        } catch (Exception e) {
            throw new Exception("调用接口url:" + url + "错误:" + e.getMessage(), e);
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsonObject;
    }
    public static void setPostHead(HttpPost httpPost, Map<String, String> headMap) {
        if (headMap != null && headMap.size() > 0) {
            Set<String> keySet = headMap.keySet();
            for (String key : keySet) {
                Object o = headMap.get(key);
                String value = (String) o;
                httpPost.addHeader(key, value);
            }
        }
    }

    private static String getRespString(HttpEntity entity) throws Exception {
        if (entity == null) {
            return null;
        }
        InputStream is = entity.getContent();
        StringBuffer strBuf = new StringBuffer();
        byte[] buffer = new byte[4096];
        int r = 0;
        while ((r = is.read(buffer)) > 0) {
            strBuf.append(new String(buffer, 0, r, "UTF-8"));
        }
        return strBuf.toString();
    }


    public static String sendPostWithBody(String url, com.alibaba.fastjson.JSONObject param) {
        BufferedReader reader = null;
        HttpURLConnection con = null;
        try {
            URL restUrl = new URL(url);
            // 打开和URL之间的连接
            con = (HttpURLConnection)restUrl.openConnection();
            //请求post方式
            con.setRequestMethod("POST");
            // Post请求不能使用缓存
            con.setUseCaches(false);
            // 设置是否从HttpURLConnection输入,默认值为 true
            con.setDoInput(true);
            // 设置是否使用HttpURLConnection进行输出,默认值为 false
            con.setDoOutput(true);

            //设置header内的参数 connection.setRequestProperty("健, "值");
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            con.setRequestProperty("Authorization","Basic " + Base64.encodeBase64String("aozhe:fda4a19a-b90d-40b0-a241-9ddece7f6f12".getBytes()));
            // 建立实际的连接
            con.connect();

            // 得到请求的输出流对象
            OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(),"UTF-8");
            writer.write(param.toString());
            writer.flush();

            // 获取服务端响应,通过输入流来读取URL的响应
            InputStream is = con.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuffer sbf = new StringBuffer();
            String strRead;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            // 打印读到的响应结果
            return sbf.toString();
        }catch (Exception e) {
            log.info("发送 POST 请求出现异常!url:{}", url, e);
        }finally {
            try {
                if(reader != null) {
                    reader.close();
                }
            }catch (IOException ex){


            }

            // 关闭连接
            if(con != null) {
                con.disconnect();
            }
        }
        return null;
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值