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. getDimension()、getDimensionPixelOffset()和getDimensionPixelSize()区别详解

    getDimension()是基于当前DisplayMetrics进行转换,获取指定资源id对应的尺寸.文档里并没说这里返回的就是像素,要注意这个函数的返回值是float,像素肯定是int. getD ...

  2. Mayi_XPath编写规则学习

    XPath编写规则学习   辅助工具:firefox安装findbugs,view Xpath firefox :Xpath验证方式:$x("xpath"); 粘贴xpath语句回 ...

  3. Css格式化/压缩(代码)

    function $() { var elements = new Array(); for (var i = 0; i < arguments.length; i++) { var eleme ...

  4. SpringBoot系列一:SpringBoot的产生

    声明:本文来源于MLDN培训视频的课堂笔记,写在这里只是为了方便查阅. 长期以来 Java 的开发一直让人所诟病: ·Java 项目开发复杂度极其高: · Java 项目的维护非常困难: · 在云时代 ...

  5. memcache -- 使用场景

    memcache:分布式缓存机制 使用场景: 1.对数据的存储要求不高,就算丢失也关系不大(因为memcache是非持久化存储) 2.不适合单机使用,即不适合将memcache和数据库等都放到同一台机 ...

  6. Winform控件学习笔记【第五天】——ListView

    [第五天] 常用的基本属性: FullRowSelect:设置是否行选择模式.(默认为false) 提示:只有在Details视图该属性才有意义. GridLines:设置行和列之间是否显示网格线.( ...

  7. ubuntu 16.04使用软件中心升级软件后桌面显示空白

    转载:http://www.jb51.net/os/Ubuntu/472560.html 每次在ubuntu Software里进行Updates后(或者直接关机后),重启电脑后,桌面显示空白 解决办 ...

  8. CentOS 7 64位更换内核安装锐速破解版

    1.更新内核 rpm -ivh http://soft.91yun.org/ISO/Linux/CentOS/kernel/kernel-3.10.0-229.1.2.el7.x86_64.rpm - ...

  9. 备份一篇SVN的文章, 从搭建到主备库

    来源: http://h2ofly.blog.51cto.com/6834926/1539141 [svn简介]            svn用于版本管理数据,它采用了分支管理系统.在它出现之前存在C ...

  10. Mac OS终端中设置颜色高亮和自动补全

    已测试通过,原文:http://blog.csdn.net/songjinshi/article/details/8945809 一.颜色高亮显示 针对terminal采用bash模式: 编辑 ~/. ...