Java-HttpClientUtils

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_31150365/article/details/85251396
import com.google.gson.GsonBuilder;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.io.IOUtils;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.*;

/**
 * @author 张昭
 * @date 2018/8/13 11:38
 */
public class HttpClientUtils {
    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

    /**
     * @param obj   JSONObject 对象的toString()字符串
     * @param url   访问路径
     * @param appId 访问UUID
     * @return
     */

    public static String httpPostWithJson(String obj, String url, String appId) {
        boolean isSuccess = false;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = null;
        String entityStr = "";
        try {

            SSLContext sslcontext = SSLContextUtils.createIgnoreVerifySSL();

            // 设置超时时间
            post = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(30000).setConnectionRequestTimeout(10000)
                    .setSocketTimeout(10000).build();
            post.setConfig(requestConfig);
            // 构造消息头
            post.setHeader("Content-type", "application/json; charset=utf-8");
            post.setHeader("Connection", "Close");
            String sessionId = getSessionId();
            post.setHeader("SessionId", sessionId);
            post.setHeader("appid", appId);

            // 构建消息实体
            StringEntity entity = new StringEntity(obj, Charset.forName("UTF-8"));
            entity.setContentEncoding("UTF-8");
            // 发送Json格式的数据请求
            entity.setContentType("application/json");
            post.setEntity(entity);

            HttpResponse response = httpClient.execute(post);
            HttpEntity entity1 = response.getEntity();
            // 使用Apache提供的工具类进行转换成字符串
            entityStr = EntityUtils.toString(entity1, "UTF-8");
            System.out.println("HttpClientUtils.httpPostWithJson.entityStr       " + entityStr);
            // 检验返回码
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                logger.info("HttpClientUtils.httpPostWithJson.请求出错: " + statusCode);
                isSuccess = false;
            } else {
                int retCode = 0;
                String sessendId = "";
                // 返回码中包含retCode及会话Id
                for (Header header : response.getAllHeaders()) {
                    if (header.getName().equals("retcode")) {
                        retCode = Integer.parseInt(header.getValue());
                    }
                    if (header.getName().equals("SessionId")) {
                        sessendId = header.getValue();
                    }
                }

                if (0 != retCode) {
                    // 日志打印
                    logger.info("HttpClientUtils.httpPostWithJson.error return code,  sessionId: " + sessendId + "retCode: " + retCode);
                    isSuccess = false;
                } else {
                    isSuccess = true;
                }
            }
        } catch (Exception e) {
            isSuccess = false;
            throw new RuntimeException(e.getMessage());
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
        return entityStr;
    }

    public static String httpPostUrlData(String obj, String url, String appId) {
        boolean isSuccess = false;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = null;
        String entityStr = "";
        try {
            // 设置超时时间
            post = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(30000).setConnectionRequestTimeout(10000)
                    .setSocketTimeout(10000).build();
            post.setConfig(requestConfig);
            // 构造消息头
            post.setHeader("Content-type", "application/json; charset=utf-8");
            post.setHeader("Connection", "Close");
            String sessionId = getSessionId();
            post.setHeader("SessionId", sessionId);
            post.setHeader("appid", appId);

            // 构建消息实体
            StringEntity entity = new StringEntity(obj, Charset.forName("UTF-8"));
            entity.setContentEncoding("UTF-8");
            // 发送Json格式的数据请求
            entity.setContentType("application/json");
            post.setEntity(entity);

            HttpResponse response = httpClient.execute(post);
            HttpEntity entity1 = response.getEntity();
            // 使用Apache提供的工具类进行转换成字符串
            entityStr = EntityUtils.toString(entity1, "UTF-8");
            System.out.println("entityStr                        " + entityStr);
            // 检验返回码
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                logger.info("请求出错: " + statusCode);
                isSuccess = false;
            } else {
                int retCode = 0;
                String sessendId = "";
                // 返回码中包含retCode及会话Id
                for (Header header : response.getAllHeaders()) {
                    if (header.getName().equals("retcode")) {
                        retCode = Integer.parseInt(header.getValue());
                    }
                    if (header.getName().equals("SessionId")) {
                        sessendId = header.getValue();
                    }
                }

                if (0 != retCode) {
                    // 日志打印
                    logger.info("error return code,  sessionId: " + sessendId + "retCode: " + retCode);
                    isSuccess = false;
                } else {
                    isSuccess = true;
                }
            }
        } catch (Exception e) {
            isSuccess = false;
            throw new RuntimeException(e.getMessage());
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
        return entityStr;
    }

    //抛出异常便于使用者try catch
    public static String httpPostUrl(String obj, String url, String appId) throws Exception {
        boolean isSuccess = false;
        HttpClient httpClient = SSLClientUtils.sslClient();
        HttpPost post = null;
        String entityStr = "";
        // 设置超时时间
        post = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(30000).setConnectionRequestTimeout(30000)
                .setSocketTimeout(30000).build();
        post.setConfig(requestConfig);
        // 构造消息头
        post.setHeader("Content-type", "application/json; charset=utf-8");
        post.setHeader("Connection", "Close");
        String sessionId = getSessionId();
        post.setHeader("SessionId", sessionId);
        post.setHeader("appid", appId);

        // 构建消息实体
        StringEntity entity = new StringEntity(obj, Charset.forName("UTF-8"));
        entity.setContentEncoding("UTF-8");
        // 发送Json格式的数据请求
        entity.setContentType("application/json");
        post.setEntity(entity);

        HttpResponse response = httpClient.execute(post);
        HttpEntity entity1 = response.getEntity();
        // 使用Apache提供的工具类进行转换成字符串
        entityStr = EntityUtils.toString(entity1, "UTF-8");
        System.out.println("entityStr                        " + entityStr);
        // 检验返回码
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            logger.info("请求出错: " + statusCode);
        } else {
            int retCode = 0;
            String sessendId = "";
            // 返回码中包含retCode及会话Id
            for (Header header : response.getAllHeaders()) {
                if (header.getName().equals("retcode")) {
                    retCode = Integer.parseInt(header.getValue());
                }
                if (header.getName().equals("SessionId")) {
                    sessendId = header.getValue();
                }
            }

            if (0 != retCode) {
                // 日志打印
                logger.info("error return code,  sessionId: " + sessendId + "retCode: " + retCode);
                isSuccess = false;
            } else {
                isSuccess = true;
            }
        }
        return entityStr;
    }

    // 构建唯一会话Id
    public static String getSessionId() {
        UUID uuid = UUID.randomUUID();
        String str = uuid.toString();
        return str.substring(0, 8) + str.substring(9, 13) + str.substring(14, 18) + str.substring(19, 23) + str.substring(24);
    }

    /**
     * Post请求,url后拼装参数
     *
     * @param url
     * @param dataMap
     * @return
     */
    public static String postParams(String url, Map<String, String> dataMap) {
        // 获取连接客户端工具
        HttpClient httpClient =SSLClientUtils.sslClient();
        String entityStr = null;
        HttpResponse response = null;
        try {

            /*
             * 添加请求参数
             */
            // 创建请求参数
            List<NameValuePair> list = new LinkedList<>();
            StringBuilder param = new StringBuilder("");
            //明文参数
            StringBuffer buffer = new StringBuffer("");
            for (Map.Entry<String, String> map : dataMap.entrySet()) {
                BasicNameValuePair param1 = new BasicNameValuePair(map.getKey(), map.getValue());
                list.add(param1);
                param.append(map.getKey() + "=" + URLEncoder.encode(map.getValue(), "UTF-8") + "&");
                buffer.append(map.getKey() + "=" + map.getValue()+" ");

            }
            // 创建POST请求对象
            HttpPost httpPost = new HttpPost(url + "?" + param.toString());
            logger.info("HttpClientUtils.postParams: "+new GsonBuilder().serializeNulls().create().toJson(dataMap));
            logger.info("HttpClientUtils.postParams: "+buffer.toString());
            logger.info("HttpClientUtils.postParams: url" + url + "?" + param.toString());
            //使用URL实体转换工具
            UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8");
            httpPost.setEntity(entityParam);
            /*
             * 添加请求头信息
             */
            // 传输的类型
            //httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            // 执行请求
            response = httpClient.execute(httpPost);
            // 获得响应的实体对象
            HttpEntity entity = response.getEntity();
            // 使用Apache提供的工具类进行转换成字符串
            entityStr = EntityUtils.toString(entity, "UTF-8");
        } catch (ClientProtocolException e) {
            logger.info("HttpClientUtils.postParams: Http协议出现问题" + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            logger.info("HttpClientUtils.postParams: IO异常" + e.getMessage());
            e.printStackTrace();
        }
        return entityStr;
    }

    /**
     * httpClient发送soap请求
     * @param url 请求地址
     * @param xml 请求参数
     * @return
     */
    public static String sendSoapRequest(String url, String xml) throws Exception{
        org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
        PostMethod postMethod = new PostMethod(url);
        // 设置连接超时
        client.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
        // 设置读取时间超时
        client.getHttpConnectionManager().getParams().setSoTimeout(30000);
        // 然后把Soap请求数据添加到PostMethod中
        StringRequestEntity requestEntity = new StringRequestEntity(xml, "application/soap+xml", "UTF-8" );

        // 设置请求体
        postMethod.setRequestEntity(requestEntity);
        int status = client.executeMethod(postMethod);
        if (status != HttpStatus.SC_OK){
            logger.info("Request "+url+" error :"+status);
        }
        // 获取响应体输入流
        InputStream is = postMethod.getResponseBodyAsStream();
        // 获取请求结果字符串
        String result = IOUtils.toString(is,"UTF-8");
        logger.info("Request "+url+" result : "+result);
        return result;
    }

    /**
     * 利用HttpClient进行post请求的工具类
     * @ClassName: HttpClientUtil
     * @Description: TODO
     * @author Devin <xxx>
     * @date 2017年2月7日 下午1:43:38
     *
     */
    @SuppressWarnings("resource")
    public static String doPost(String url,String jsonstr,String charset){
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try{
            httpClient = SSLClientUtils.sslClient();
            httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");

            httpPost.setHeader("Accept", "application/json");
            httpPost.setEntity(new StringEntity(jsonstr, Charset.forName("UTF-8")));
            //解決乱码
           /* StringEntity se = new StringEntity(jsonstr);
            se.setContentType("text/json");
            se.setContentEncoding(new BasicHeader("Content-Type", "application/json;charset=UTF-8"));
            httpPost.setEntity(se);*/
            HttpResponse response = httpClient.execute(httpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
                    logger.info("HttpClientUtils.doPost result :"+result);
                }
            }
        }catch(Exception ex){
            logger.error("HttpClientUtils.doPost exception :"+SystemUtil.getExceptionMsg(ex));
        }
        return result;
    }

    public static void main(String[] args) {
        Map<String, String> dataMap = new HashMap<>();
        dataMap.put("json", "asdfasdf sfdsdfsdf");
        HttpClientUtils.postParams("http://10.11.14.157:8080/FHReservation/test", dataMap);
    }


}

猜你喜欢

转载自blog.csdn.net/qq_31150365/article/details/85251396
今日推荐