HttpClientUtils.java 8.1 KB
package com.cnlive.shenhe.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
public class HttpClientUtils {
    public static String post(String url, Map<String, Object> map) {
        // 创建post请求
        HttpPost post = new HttpPost(url);
        String text = "请求失败";
        try {
            // 创建http访问的客户端
            HttpClient client = HttpClients.createDefault();
            List<NameValuePair> param = new ArrayList<>();
            if(map!=null&&map.size()>0){
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    param.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
                }
            }
            // 用参数构造请求实体
            HttpEntity postEntity = new UrlEncodedFormEntity(param, "utf-8");
            // 把请求实体放到post请求中
            post.setEntity(postEntity);
            // 执行post请求
            HttpResponse response = client.execute(post);
            // 从响应中取得一个响应实体
            HttpEntity entity = response.getEntity();
            // 把响应实体转成文本信息
            text = EntityUtils.toString(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            post.releaseConnection();// 释放连接
        }
        return text;
    }

    public static String get(String url) {
        String text = "请求失败";
        HttpGet httpGet = null;
        try {
            // 创建http访问的客户端
            HttpClient client = HttpClients.createDefault();
            httpGet = new HttpGet(url);
            // 执行get请求
            HttpResponse response = client.execute(httpGet);
            // 从响应中取得一个响应实体
            HttpEntity entity = response.getEntity();
            // 把响应实体转成文本信息
            text = EntityUtils.toString(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpGet.releaseConnection();// 释放连接
        }
        return text;
    }

    public static String get(String url, Map<String, String> map) {
        String text = "请求失败";
        HttpGet httpGet = null;
        try {
            // 创建http访问的客户端
            HttpClient client = HttpClients.createDefault();
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            if (map != null && map.size() > 0) {
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }
            String paramsStr = EntityUtils.toString(new UrlEncodedFormEntity(params, "UTF-8"));
            httpGet = new HttpGet(url + "?" + paramsStr);
            // 执行get请求
            HttpResponse response = client.execute(httpGet);
            // 从响应中取得一个响应实体
            HttpEntity entity = response.getEntity();
            // 把响应实体转成文本信息
            text = EntityUtils.toString(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpGet.releaseConnection();// 释放连接
        }
        return text;
    }

    public static String post_str(String url, Map<String, String> map) {
        HttpPost post = null;
        String text = "请求失败";
        try {
            // 创建http访问的客户端
            HttpClient client = HttpClients.createDefault();
            List<NameValuePair> param = new ArrayList<>();
            if (map != null && map.size() > 0) {
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    param.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }
            // 用参数构造请求实体
            HttpEntity postEntity = new UrlEncodedFormEntity(param, "utf-8");
            // 创建post请求
            post = new HttpPost(url);
            // 把请求实体放到post请求中
            post.setEntity(postEntity);
            // 执行post请求
            HttpResponse response = client.execute(post);
            // 从响应中取得一个响应实体
            HttpEntity entity = response.getEntity();
            // 把响应实体转成文本信息
            text = EntityUtils.toString(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放连接
            post.releaseConnection();
        }
        return text;
    }

    public static String HttpPostWithJson(String url, String json) {

        CloseableHttpClient httpClient = null;
        try {
            httpClient = HttpClients.createDefault();

            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/json;charset=utf-8");

            StringEntity se = new StringEntity(json, "UTF-8");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            httpPost.setEntity(se);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // 返回数据
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "UTF-8");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * httpPost
     * @param url           请求url
     * @param jsonParam
     * @param noNeedResponse  是否获取接口response
     * @return
     * @throws Exception
     */
    public static JSONObject httpPost(String url, JSONObject jsonParam, boolean noNeedResponse) throws Exception{
        CloseableHttpClient httpClient = HttpClients.createDefault();

        JSONObject jsonResult = null;
        HttpPost method = new HttpPost(url);
        try {
            if (null != jsonParam) {
                StringEntity entity = new StringEntity(jsonParam.toString(), "UTF-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
            if (result.getStatusLine().getStatusCode() == 200) {
                String str = "";
                try {
                    str = EntityUtils.toString(result.getEntity());
                    if (noNeedResponse) {
                        return null;
                    }
                    jsonResult = JSON.parseObject(str);
                } catch (Exception e) {
                    System.out.println("posturl:" + url + ", err=" + e.getMessage());
                    throw new Exception(e);
                }
            }
        } catch (IOException e) {
            System.out.println("posturl:" + url + ", err=" + e.getMessage());
            throw new IOException(e);
        }
        return jsonResult;
    }


}