HttpClient 通信工具类
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 通信工具类的更多相关文章
- Https通信工具类
记录一个在微信开发中用到的https通信工具类,以后会用到的. 用于https通信的证书信任管理器 import java.security.cert.CertificateException; im ...
- java并发编程系列原理篇--JDK中的通信工具类Semaphore
前言 java多线程之间进行通信时,JDK主要提供了以下几种通信工具类.主要有Semaphore.CountDownLatch.CyclicBarrier.exchanger.Phaser这几个通讯类 ...
- HttpClient封装工具类
import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.List; ...
- HttpClient请求工具类
package com.yangche.utils; import org.apache.http.NameValuePair; import org.apache.http.client.Clien ...
- Android 蓝牙串口通信工具类 SerialPortUtil 3.0.+
建议使用4.+版本,避免一些不必要的bug.4.+版本文档地址:https://www.cnblogs.com/shanya/articles/16062256.html SerialPortUtil ...
- 使用单例模式实现自己的HttpClient工具类
引子 在Android开发中我们经常会用到网络连接功能与服务器进行数据的交互,为此Android的SDK提供了Apache的HttpClient 来方便我们使用各种Http服务.你可以把HttpCli ...
- Android开发实现HttpClient工具类
在Android开发中我们经常会用到网络连接功能与服务器进行数据的交互,为此Android的SDK提供了Apache的HttpClient来方便我们使用各种Http服务.你可以把HttpClient想 ...
- http和https工具类 (要注意httpclient版本号和log4j的版本号)
1 工具类 package dd.com; import java.io.IOException; import java.security.cert.CertificateException; im ...
- 基于HttpClient4.5.2实现的HttpClient工具类
1.maven依赖: <dependency> <groupId>org.apache.commons</groupId> <artifactId>co ...
随机推荐
- Qt中与文件目录相关操作
一.与文件目录操作有关操作. Qt中与文件目录相关的操作在QDir中,需加入#include <QDir>语句. QDir::drives()是列出电脑根目录下的所有目录,返回的是QFil ...
- USB学习笔记连载(十一):CY7C68013A的启动方式-EEPROM
上述的应用笔记中有介绍FX2LP的启动选项,主要包括I2C启动和USB启动. 说白了I2C启动需要使用外部的EEPROM,USB启动,只是使用上位机控制软件将配置程序FX2LP中,不用EEPRO ...
- 提供openssl -aes-256-cbc兼容加密/解密的简单python函数
原文链接:http://joelinoff.com/blog/?p=885 这里的示例显示了如何使用python以与openssl aes-256-cbc完全兼容的方式加密和解密数据.它是基于我在本网 ...
- Ext3.4实现增删查改(form版)
var TaskPolicyStore = new Ext.data.JsonStore( { autoLoad : false, url : 'PolicyServlet?method= ...
- SAP+ 差旅报销集成方案的实现
跨国集团通常都会有一个财务共享中心SSC的集中处理业务部门,用于统计来自各个公司的差旅报销,而1).传统的OA审批 虽然审批流是优势存在着需要SAP数据二次录入,数据不同步等困难,2).如果终端用户都 ...
- Unity--------------------万向锁的概念
万向锁 一直困惑我很久....原因出在这里,我以为欧拉角旋转是以模型坐标(齐次坐标系)为旋转轴.问题就来了,无论旋转那个轴,其它两个轴也会相应的变化,下面看图: 根据上面的说明两个旋转面(圆圈)怎么会 ...
- php -- 取整数
PHP取整数函数常用的四种方法,下面收集了四个函数: 经常用到取整的函数,今天小小的总结一下!其实很简单,就是几个函数而已--主要是:ceil,floor,round,intval ceil — 进一 ...
- Oracle数据库order by排序查询分页比不分页还慢问题解决办法
简单说下问题,有一个JDBC的查询SQL,分页查询语句中有一个排序order by create_time,理论上来说JDBC查询已经是比较底层的技术了,没有像Hibernate.MyBatis那样又 ...
- [原创]RX801SJ 实时时钟RTC调试纪要 : 时钟输出设置
利用USB转I2C/SPI/UART板进行通信测试 1.RX8010SJ的I2C通信地址定义如下: 设备读取地址:0X65 设备写入地址:0X64 2.USB2ish0转接板操作界面如下: 3.参 ...
- vncviewer 通过ipv6连接
vncserver 填为: [ipv6-address]:port 即可,例如 [:da8::81f:f292:1cff:fe07:da3c]: