package com.taotao.web.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
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.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ApiService {

    //定义日志信息
    private static final Logger LOGGER = LoggerFactory.getLogger(ApiService.class);
    @Autowired
    private CloseableHttpClient httpClient;

    @Autowired
    private RequestConfig requestConfig;

    //执行get 请求
    public String doGet(String url) throws Exception {
         LOGGER.info("执行GET请求,URL = {}", url);
         //创建GET请求
         HttpGet httpGet = new HttpGet(url);
         httpGet.setConfig(requestConfig);
         CloseableHttpResponse response = null;
         try {
             // 执行请求
             response = httpClient.execute(httpGet);
             // 判断返回状态是否为200
             if (response.getStatusLine().getStatusCode() == 200) {
                 return EntityUtils.toString(response.getEntity(), "UTF-8");
             }
         } finally {
             if (response != null) {
                 response.close();
             }
             // 此处不能关闭httpClient,如果关闭httpClient,连接池也会销毁
         }
         return null;
     }
        //带有参数的请求
    public String doGet(String url, Map<String, String> params) throws Exception{
        URIBuilder  builder=new URIBuilder(url);
        for (Map.Entry<String,String > entry : params.entrySet()) {
            builder.setParameter(entry.getKey(),entry.getValue());
        }
         return doGet(builder.build().toString());
    }

    //执行POST请求
    public String doPost(String url, Map<String, String> params) throws Exception {
        // 创建http POST请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);

        if (null != params) {
            // 设置2个post参数,一个是scope、一个是q
            List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
            for (Map.Entry<String, String> entry : params.entrySet()) {
                parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }

            // 构造一个form表单式的实体
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
            // 将请求实体设置到httpPost对象中
            httpPost.setEntity(formEntity);
        }

        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpClient.execute(httpPost);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return null;
    }
    public String doPost(String url, Map<String, String> params,String encode) throws Exception {
        // 创建http POST请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);

        if (null != params) {
            // 设置2个post参数,一个是scope、一个是q
            List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
            for (Map.Entry<String, String> entry : params.entrySet()) {
                parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }

            // 构造一个form表单式的实体
            UrlEncodedFormEntity formEntity = null;
            if(encode!=null){
                formEntity = new UrlEncodedFormEntity(parameters,encode);
            }else{
                formEntity = new UrlEncodedFormEntity(parameters);
            }
            // 将请求实体设置到httpPost对象中
            httpPost.setEntity(formEntity);
        }

        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpClient.execute(httpPost);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return null;
    }
    public String doPostJson(String url, String json) throws Exception {
        // 创建http POST请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);

        if(null != json){
            //设置请求体为 字符串
            StringEntity stringEntity = new StringEntity(json,"UTF-8");
            httpPost.setEntity(stringEntity);
        }

        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpClient.execute(httpPost);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return null;
    }

}
    

HttpClient 通信工具类的更多相关文章

  1. Https通信工具类

    记录一个在微信开发中用到的https通信工具类,以后会用到的. 用于https通信的证书信任管理器 import java.security.cert.CertificateException; im ...

  2. java并发编程系列原理篇--JDK中的通信工具类Semaphore

    前言 java多线程之间进行通信时,JDK主要提供了以下几种通信工具类.主要有Semaphore.CountDownLatch.CyclicBarrier.exchanger.Phaser这几个通讯类 ...

  3. HttpClient封装工具类

    import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.List; ...

  4. HttpClient请求工具类

    package com.yangche.utils; import org.apache.http.NameValuePair; import org.apache.http.client.Clien ...

  5. Android 蓝牙串口通信工具类 SerialPortUtil 3.0.+

    建议使用4.+版本,避免一些不必要的bug.4.+版本文档地址:https://www.cnblogs.com/shanya/articles/16062256.html SerialPortUtil ...

  6. 使用单例模式实现自己的HttpClient工具类

    引子 在Android开发中我们经常会用到网络连接功能与服务器进行数据的交互,为此Android的SDK提供了Apache的HttpClient 来方便我们使用各种Http服务.你可以把HttpCli ...

  7. Android开发实现HttpClient工具类

    在Android开发中我们经常会用到网络连接功能与服务器进行数据的交互,为此Android的SDK提供了Apache的HttpClient来方便我们使用各种Http服务.你可以把HttpClient想 ...

  8. http和https工具类 (要注意httpclient版本号和log4j的版本号)

    1 工具类 package dd.com; import java.io.IOException; import java.security.cert.CertificateException; im ...

  9. 基于HttpClient4.5.2实现的HttpClient工具类

    1.maven依赖: <dependency> <groupId>org.apache.commons</groupId> <artifactId>co ...

随机推荐

  1. Qt实现探测当前有没有网络连接(Wi-Fi)——QNetworkConfigurationManager.isOnline()

    1.只需要探测当前有没有连上Wi-Fi(不用获取网络状态),可以调用<QNetworkConfigurationManager>类. QNetworkConfigurationManage ...

  2. c数组

    一维数组 有三种赋值方式 1.原始的赋值 2. 初始化赋值 3.动态赋值 数组的花式玩法 void main() { ] = {, , , , , , , , , }; test(a); putcha ...

  3. Android 8 Wifi 初始化过程

    记录一下wifi初始化过程. packages/apps/Settings/src/com/android/settings/wifi/WifiSettings.java public void on ...

  4. Java如何设定二维数组的上限?

    在Java中,如何设定二维数组的上限? 以下示例中,使用arrayname.length来确定二维数组的上限(元素数目). package com.yiibai; public class Dimen ...

  5. (转)ffmpeg 中 av_read_frame_internal分析

    作者: chenwei1983    时间: 2012-3-5 04:21 PM标题: ffmpeg 中 av_read_frame_internal分析                       ...

  6. Linux CPU Load Average

    理解Linux系统负荷 LINUX下CPU Load Average的一点研究 Linux load average负载量分析与解决思路 Understanding Linux CPU Load - ...

  7. 使用w查看系统负载 vmstat命令 top命令 sar命令 nload命令

    w/uptime 查看系统负载 w查看系统负载,uptime跟w一样. [root@centos7 ~]# w 22:34:10 up 6 days, 23:10,  4 users,  load a ...

  8. MD5 哈希等各种加密方式 都是对这个对象进行各种运算, 然后得出1个字符串

    你列出的4个  都是对对象的 加密算法

  9. 通过tarball形式安装HBASE Cluster(CDH5.0.2)——如何配置分布式集群中的zookeeper

    集群安装总览参见这里 Zookeeper的配置 1,/etc/profile中加入zk的路径设置,见上面背景说明. 2,进入~/zk/conf目录,复制zoo_sample.cfg为zoo.cfg v ...

  10. Oracle With As 查询

    WITH AS WITH AS短语,也叫做子查询部分(subquery factoring),可以让你做很多事情,定义一个SQL片断,该SQL片断会被整个SQL语句所用到.有的时候,是为了让SQL语句 ...