基于HttpClient的远程调用工具类

1.需要导入的依赖包

           <!-- httpclient 依赖-->
       <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.12</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.2</version>
        </dependency>

      <!-- fastjson  依赖-->
      <dependency>
           <groupId>com.alibaba</groupId>
           <artifactId>fastjson</artifactId>
           <version>1.2.78</version>
      </dependency>


2.HttpClient工具类

package com.loit.modules.stat.util;

import com.alibaba.fastjson.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.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
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.client.utils.URLEncodedUtils;
import org.apache.http.entity.ContentType;
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 java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 模拟http请求工具类
 *
 * @author zhangyinglu
 */
public class HttpUtil {

    


    /**
     * Get请求    无参
     *
     * @param url 请求地址
     * @return String
     * @author zhangyinglu
     */
    public static String doGet4String(String url) {
        try {
            HttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) {
                HttpEntity httpEntity = httpResponse.getEntity();
                String strResult = EntityUtils.toString(httpEntity, "UTF-8");

                return strResult;
            }
        } catch (Exception e) {
            
        }

        return null;
    }


    /**
     * get请求 + 表单类型参数
     * @param url
     * @param map
     * @return
     */
    public static String doGetUkString(String url, Map<String, String> map) {
        try {
            List<NameValuePair> params = map.entrySet().stream().map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue())).collect(Collectors.toList());
            URI uri = new URI(url + "?" + URLEncodedUtils.format(params, "UTF-8"));
            HttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(uri);
//            httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded");
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String strResult = EntityUtils.toString(httpEntity, "UTF-8");
            if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) {
                return strResult;
            }
        } catch (Exception e) {
            
        }

        return null;
    }



    /**
     * get请求  +  表单类型参数  +  自定义请求头
     * @param url
     * @param map
     * @param headerMap   例如 headerMap.put("Authorization",accessToken);
     * @return
     */
    public static String doGetUkHeaderString(String url, Map<String, String> map, Map<String, Object> headerMap) {
        try {
            List<NameValuePair> params = map.entrySet().stream().map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue())).collect(Collectors.toList());
            URI uri = new URI(url + "?" + URLEncodedUtils.format(params, "UTF-8"));
//            URI uri1 = new URI("http://10.156.90.41:8088/VIID/query?org=iccsid&condition=%7B%22ItemNum%22%3A3%2C%22Condition%22%3A%5B%7B%22QueryType%22%3A256%2C%22LogicFlag%22%3A0%2C%22QueryData%22%3A%221%22%7D%2C%7B%22QueryType%22%3A257%2C%22LogicFlag%22%3A0%2C%22QueryData%22%3A%221%22%7D%2C%7B%22QueryType%22%3A1%2C%22LogicFlag%22%3A5%2C%22QueryData%22%3A%22%22%7D%5D%2C%22QueryCount%22%3A%221%22%2C%22PageFirstRowNumber%22%3A%220%22%2C%22PageRowNum%22%3A%2210%22%7D");
            HttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(uri);
//            httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded");
            if (headerMap != null) {
                for (String key : headerMap.keySet()) {
                    if (headerMap.get(key) != null) {
                        httpGet.addHeader(key, String.valueOf(headerMap.get(key)));
                    }
                }
            }
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String strResult = EntityUtils.toString(httpEntity, "UTF-8");
            if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) {
                return strResult;
            }
        } catch (Exception e) {
            
        }

        return null;
    }


    /**
     * get请求  +  json格式参数 +  指定请求头 (这个方法没测试!!!慎用!!!!!)
     * @param url
     * @param jsonString
     * @param headerMap
     * @return
     * @throws IOException
     */
    public static String doGetUkHeaderStringJson(String url, String jsonString, Map<String, Object> headerMap) {
        try{
            String body = "";
            //创建httpclient对象
            CloseableHttpClient client = HttpClients.createDefault();
            HttpGetWithEntity httpGetWithEntity = new HttpGetWithEntity(url);
            HttpEntity httpEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
            httpGetWithEntity.setEntity(httpEntity);
            if (headerMap != null) {
                for (String key : headerMap.keySet()) {
                    if (headerMap.get(key) != null) {
                        httpGetWithEntity.addHeader(key, String.valueOf(headerMap.get(key)));
                    }
                }
            }
            //执行请求操作,并拿到结果
            CloseableHttpResponse response = client.execute(httpGetWithEntity);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, "UTF-8");
            }
            //释放链接
            response.close();
            return body;
        } catch (Exception e) {
        }
        return null;

    }


    /**
     * Post请求   无参
     *
     * @param url 请求地址
     * @return String
     * @author zhangyinglu
     */
    public static String doPost4String(String url) {
        try {
            HttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) {
                HttpEntity httpEntity = httpResponse.getEntity();
                String strResult = EntityUtils.toString(httpEntity, "UTF-8");
                return strResult;
            }
        } catch (Exception e) {
        }

        return null;
    }

    /**
     * post请求  +  json格式参数
     * @param url
     * @param jsonString
     * @return
     */
    public static String doPostuKString(String url, String jsonString) {
        try {
            HttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            StringEntity stringEntity = new StringEntity(jsonString, "UTF-8");
            httpPost.setEntity(stringEntity);
//			httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            String strResult = EntityUtils.toString(httpEntity, "UTF-8");
            if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) {
                return strResult;
            }
        } catch (Exception e) {
        }

        return null;
    }

    /**
     * Post请求  +  json格式参数  +  设置超时时间
     *
     * @param url        请求地址
     * @param jsonString 请求参数
     * @return String
     * @author zhangyinglu
     */
    public static String doPost4String(String url, String jsonString) {
        try {
            HttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000).setConnectionRequestTimeout(1000).setSocketTimeout(3000).build();
            httpPost.setConfig(requestConfig);
            StringEntity stringEntity = new StringEntity(jsonString, "UTF-8");
            httpPost.setEntity(stringEntity);
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            
            if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) {
                String strResult = EntityUtils.toString(httpEntity, "UTF-8");
                return strResult;
            }
        } catch (Exception e) {
        }

        return null;
    }

    /**
     * Post请求 +  json格式参数   +   自定义请求头
     *
     * @param url        请求地址
     * @param jsonString 请求参数
     * @param headerMap  请求头
     * @return String
     * @author zhangyinglu
     */
    public static String doPost4String2(String url, String jsonString, Map<String, Object> headerMap) {
        try {
            HttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000).setConnectionRequestTimeout(1000).setSocketTimeout(3000).build();
            httpPost.setConfig(requestConfig);
            StringEntity stringEntity = new StringEntity(jsonString, "UTF-8");
            httpPost.setEntity(stringEntity);
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
            if (headerMap != null) {
                for (String key : headerMap.keySet()) {
                    if (headerMap.get(key) != null) {
                        httpPost.addHeader(key, String.valueOf(headerMap.get(key)));
                    }
                }
            }
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) {
                String strResult = EntityUtils.toString(httpEntity, "UTF-8");
                return strResult;
            }
        } catch (Exception e) {
        }

        return null;
    }

    /**
     * Get请求返回Json
     *
     * @param url 请求地址
     * @return JSONObject
     * @author zhangyinglu
     */
    public static JSONObject doGet4Json(String url) {
        try {
            return JSONObject.parseObject(doGet4String(url));
        } catch (Exception e) {
        }

        return null;
    }

    /**
     * Post请求返回Json
     *
     * @param url 请求地址
     * @return JSONObject
     * @author zhangyinglu
     */
    public static JSONObject doPost4Json(String url) {
        try {
            return JSONObject.parseObject(doPost4String(url));
        } catch (Exception e) {
        }

        return null;
    }

}

  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值