import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpClientUtils {

private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

private static final String ENCODING = "utf-8";

/**
* 发送 get请求
*/
public static String get(String url,String encoding,String headerKeyValue) {
encoding = null == encoding ? ENCODING : encoding;
CloseableHttpClient httpclient = HttpClients.createDefault();
String responseStr = null;
try {
// 创建httpget.
HttpGet httpget = new HttpGet(url);
if(!StringUtils.isEmpty(headerKeyValue)){
String[] headerKeyValueArr = headerKeyValue.split(";");
for (String keyValue : headerKeyValueArr) {
String[] KeyValueArr = keyValue.split("=");
if("Content-Type".equals(KeyValueArr[0]))
httpget.addHeader(KeyValueArr[0], KeyValueArr[1]+";charset="+encoding);
else
httpget.addHeader(KeyValueArr[0], KeyValueArr[1]);
}
}
logger.info("executing request :" + httpget.getURI());
// 执行get请求.
CloseableHttpResponse response = httpclient.execute(httpget);

// 打印响应状态
System.out.println("-------- :"+response.getStatusLine());
int responseCode = response.getStatusLine().getStatusCode();

if(responseCode != 200 ) return responseStr;
// 获取响应实体
HttpEntity entity = response.getEntity();

if (entity == null) return responseStr;
responseStr = EntityUtils.toString(entity,encoding);

// 打印响应内容长度
logger.info("Response content length: " + entity.getContentLength());
// 打印响应内容
logger.info("Response content: " +responseStr );
return responseStr;
} catch (ClientProtocolException e) {
logger.error("........httpget request error : " + e);
e.printStackTrace();
} catch (ParseException ee) {
logger.error("........httpget request error : " + ee);
ee.printStackTrace();
} catch (IOException eee) {
logger.error("........httpget request error : " + eee);
eee.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return responseStr;
}

/**
* 发送 post请求
*/
public static String post(String url ,List<NameValuePair> params,String encoding,String headerKeyValue) {
encoding = null == encoding ? ENCODING : encoding;
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
String responseStr = null;
try {
// 创建httppost
HttpPost httppost = new HttpPost(url);
if(!StringUtils.isEmpty(headerKeyValue)){
String[] headerKeyValueArr = headerKeyValue.split(";");
for (String keyValue : headerKeyValueArr) {
String[] KeyValueArr = keyValue.split("=");
if("Content-Type".equals(KeyValueArr[0]))
httppost.addHeader(KeyValueArr[0], KeyValueArr[1]+";charset="+encoding);
else
httppost.addHeader(KeyValueArr[0], KeyValueArr[1]);
}
}
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(params, encoding);
httppost.setEntity(uefEntity);
logger.info("executing request :" + httppost.getURI());

CloseableHttpResponse response = httpclient.execute(httppost);
// 打印响应状态
System.out.println("-------- :"+response.getStatusLine());
int responseCode = response.getStatusLine().getStatusCode();
if(responseCode != 200 ) return responseStr;

HttpEntity entity = response.getEntity();
if (entity == null) return responseStr;
responseStr = EntityUtils.toString(entity, encoding);
logger.info("Response content : " + responseStr);
return responseStr;
} catch (ClientProtocolException e) {
logger.error("........httppost request error : " + e);
e.printStackTrace();
} catch (UnsupportedEncodingException ee) {
logger.error("........httppost request error : " + ee);
ee.printStackTrace();
} catch (IOException eee) {
logger.error("........httppost request error : " + eee);
eee.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return responseStr;
}
}

HttpClientUtils的更多相关文章

  1. HttpClientUtils.java

    package com.vcredit.ddcash.batch.util; import java.io.BufferedReader;import java.io.ByteArrayOutputS ...

  2. 包括post,get请求(http,https)的HttpClientUtils

    package cn.knet.data.untils; import java.io.IOException; import java.net.SocketTimeoutException; imp ...

  3. 简单HttpClientUtils工具类

    package com.zy.utils; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import o ...

  4. Web 开发工具类(2): HttpClientUtils

    HttpClientUtils 整合了一些 web开发中常用的httpClient操作: package com.evan.common.utils; import java.io.IOExcepti ...

  5. coding++ :HttpClientUtils 封装

    1.关键 JAR  <!-- <<===================>> httpClient <<===================>> ...

  6. HttpClientUtils:Http请求工具类

    HttpClientUtils:Http请求工具类 Scala:HttpClientUtils Scala:HttpClientUtils import java.io.IOException imp ...

  7. 强大的httpClientUtils

    <!-- https://mvnrepository.com/artifact/com.arronlong/httpclientutil --> <dependency> &l ...

  8. Restful 介绍及SpringMVC+restful 实例讲解

    restful不是一个框架,称为一种编码更烦更贴切吧,其核心类位于spring-web.jar中,即RestTemplate.class restful是rpc通过http协议的一种实现方式,和web ...

  9. 【tomcat】HTTPS访问配置 + restful调用远程HTTPS绕过验证

     单向验证: 第一步: 生成key: keytool -genkey -alias mykey -keyalg RSA -keystore d:/key/testkey keytool -export ...

随机推荐

  1. SQL 语言 - 数据库系统原理

    SQL 发展历程 从 1970 年美国 IBM 研究中心的 E.F.Codd 发表论文到 1974 年 Boyce 和 Chamberlin 把 SQUARE 语言改为 SEQUEL 语言,到现在的 ...

  2. java关键字:synchronized

    JAVA 如何共享资源 关于synchronized函数: java具有内置机制,可防止某种资源(此处指的是对象的内存内容)冲突.由于你通常会将某class的数据元素声明为private,并且只经由其 ...

  3. [API]使用Blueprint来高雅的编写接口文档 前后端api文档,移动端api文档

    网址:http://apiary.io/ 介绍:一款非常强大的前后端交互api设计编辑工具(编辑器采用Markdown类似的描述标记,非常高效),高颜值的api文档,还能生成多种语言的测试代码. 中文 ...

  4. About SSDT BI

    Welcome to Microsoft Marketing Speak hell. With the 2012 release of SQL Server, the BIDS, Business I ...

  5. logstash无法使用conf启动

    最近刚开始学习使用logstash,再安装好后准备验证下第一个demo的时候,出现了问题 Error: Expected one of #, input, filter, output at line ...

  6. lumen 构建api(dingo api)

    什么是 API API(Application Programming Interface,应用程序编程接口)是一些预先定义的函数,目的是提供应用程序与开发人员基于某软件或硬件得以访问一组例程的能力, ...

  7. 公用表表达式(CTE)递归的生成帮助数据

    本文的作者辛苦了,版权问题特声明本文出处:http://www.cnblogs.com/wy123/p/5960825.html 工作有时候会需要一些帮助数据,必须需要连续的数字,连续间隔的时间点,连 ...

  8. 【DNS】简单聊聊DNS如何工作

    随便聊聊 我们知道,网络上传输的数据包是一层一层的包起来的,典型的是mac地址层,ip层,tcp/udp层,应用层数据 这么几个层,那用户在浏览器中打开www.baidu.com数据包如何传到baid ...

  9. 使用PowerDesigner把oom设计图导出jpg格式的图片

    1: 按住Shift键点击鼠标选择要导出的对象,必须先选择. 2: 选择Edit—>Export Image 到出你需要的格式,如下图

  10. git学习1:git安装和配置

    Git是什么?世界上最先进的分布式版本控制系统,记录了一个文本文件的每次一修改信息,比如,一篇散文,从草稿到最终出版,经历过无数次修改,修改了标点符号形成一个版本,老师帮助修改形成一个版本,同学帮忙修 ...