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. USB2.0学习笔记连载(九):USB设备驱动的安装

    在第一次插入USB设备时(笔者用的是自己做的USB最小系统来测试),插入电脑后,在设备管理器中会显示 未知设备,如下图所示: 点击右键,选择属性,在详细信息中可以看到硬件ID以及PID等,如下图所示. ...

  2. ASK,OOK,FSK的联系和区别

    转自:http://www.cnblogs.com/zhihongyu/archive/2012/04/12/2443617.html ASK是幅移键控调制的简写,例如二进制的,把二进制符号0和1分别 ...

  3. Html中怎么用CSS让ul中多个li标签不换行横排显示

    布局 通常有三种方式 { 1. position 2. float: left --> 其次是这个 3. block: inline-block  --> 他们推荐我用这个 } 具体描述 ...

  4. 基于jquery的ui选择之路

    选定: 主框架:jqueryUi tree:ztree grid:jqGrid layout:jquery.layout 原由: 还有其他demo,ajax实现等参看连接: 正在做的一个项目选择jqu ...

  5. Simsimi 小黄鸡机器人最新无限制接口api simsimi机器人接口api 微信公众号

    一.什么是Simsimi? simsimi公司是提供智能服务,其中一个服务是simsimi聊天机器人服务,每天有超过百万的用户聊天,国内最大的搜索引擎——百度的产品siri使用的就是simsimi提供 ...

  6. SpringBoot学习:使用spring-boot-devtools进行热部署

    项目下载地址:http://download.csdn.net/detail/aqsunkai/9805821 pom.xml添加依赖: <!--支持热启动jar包--> <depe ...

  7. 植物 miRNA 研究

    相比动物miRNA 而言, 植物miRNA 的研究相对较少. 植物miRNA 相比动物miRNA , 有以下特点: 1) 植物miRNA 的长度为 21 nt 左右, 动物miRNA 长度在 22 ~ ...

  8. 每天一个linux命令:cat 命令

    cat命令的用途是连接文件或标准输入并打印.这个命令常用来显示文件内容,或者将几个文件连接起来显示,或者从标准输入读取内容并显示,它常与重定向符号配合使用. 1.命令格式: cat [选项] [文件] ...

  9. win 10中打开sql server配置管理器

    转自: https://www.cnblogs.com/He-tao-yuan/p/6744412.html

  10. PHP中全局变量的使用global和$GLOBALS[]

    From: http://blog.csdn.net/happyqyt/article/details/7219889 用PHP开发项目,不可避免的会使用到全局变量,比如一些网站的配置信息,全站通用, ...