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. HBase高性能复杂条件查询引擎

    转自:http://blog.csdn.net/bluishglc/article/details/31799255 mark 写在前面 本文2014年7月份发表于InfoQ,HBase的PMC成员T ...

  2. 关于Unity中的光照(五)

    Mobile Diffuse Unity自带的一种shader,用的比较多,性能还可以.我们默认创建的unit shader基本和它一致,但是没有参与光照计算,看起来和Mobile Diffuse有区 ...

  3. Java如何格式化秒数?

    在Java中,如何格式化秒数? 此示例使用SimpleDateFormat类的SimpleDateFormat('ss')构造函数和sdf.format(date)方法格式化秒数. package c ...

  4. e803. 获得和设置JProgressBar的值

    // To create a progress bar, see e801 创建一个JProgressBar组件 // Get the current value int value = progre ...

  5. Websphere多个应用session相互覆盖问题解决办法

    原文链接:http://my.oschina.net/moyuqi/blog/98475 使用apache反向代理解决在应用A使用Iframe嵌入应用B的功能而产生的跨域问题后,应用B的功能能正常使用 ...

  6. linux 系统安装配置 zabbix服务(源码安装)

    简介: zabbix是一个基于WEB界面的提供分布式系统监视以及网络监视功能的企业级的开源解决方案. zabbix能监视各种网络参数,保证服务器系统的安全运营:并提供灵活的通知机制以让系统管理员快速定 ...

  7. motiMaker 软件安装测试

    背景: mitoMaker是一款线粒体/叶绿体组装的pipeline软件,可以从原始的下机数据开始,自动化的组装基因组,注释基因结构,最终生成genebank, fasta 等文件. 整个pipeli ...

  8. ggplot2 提取stat计算出来的数据

    使用ggplot2 绘图时,我们只需要提供原始数据就可以了,ggplot2 内置了许多的计算函数,来帮助我们计算对应的数值. 最典型的的,当使用geom_boxplot 绘制箱线图时,我们只提供原始数 ...

  9. spring中基于aop使用ehcache

    我就是对着这个博客看的 http://www.cnblogs.com/ctxsdhy/p/6421016.html

  10. pycharm环境下:同文件夹下文件(.py)之间的调用,出现红线问题

    只要将pycharm下打开项目后: 将你运行文件(.py)的项目设置为根目录,就不会出现红色线: