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. javascript的this

    关于JavaScript中的this的取值: 函数在创建的时候,会创建两个隐藏属性:函数的上下文.实现函数行为的代码(调用属性):以及prototype属性.length属性. 函数在调用的时候,除了 ...

  2. winform中button的image属性无法更改

    在开发一个winform程序的时候,界面中的button的image本来有一个贴图A.后来我觉得不合适,打算换成贴图B. 但是这时问题出现了:虽然我改成了贴图B,在IDE中的预览也是贴图B,但是每次编 ...

  3. vm centos 网络配置

    安装Centos系统,查看网络配置. 输入命令:ifconfig 127.0.0.1 要开启网络 进入ifcfg-eth0文件. 输入命令:vi /etc/sysconfig/network-scri ...

  4. Reed-Solomon码,QR

    原文: Reed–Solomon codes for coders参考: AN2407.pdfWIKI: 里德-所罗门码实现:Pypi ReedSolo #译注:最近看到了RS码,发现还挺有意思的,找 ...

  5. 10天学会phpWeChat——第七天:创建一个自适应PC网站+H5移动端的模块

    本教程基于phpWeChat核心框架1.1.0+版本.下载地址:http://s.phpwechat.com/app_38026ed22fc1a91d92b5d2ef93540f20 通过前面六讲的系 ...

  6. k8s dashboard 部署发布

    https://rawgit.com/kubernetes/dashboard/master/src/deploy/kubernetes-dashboard.yaml # Copyright 2015 ...

  7. OPENVPN

    安装 方法1--源码安装yum -y install  pam pam-devel gcc gcc-c++ lzo lzo-devel openssl openssl-devel wget autom ...

  8. 发布 Ionic iOS 企业级应用

    转自:http://www.jianshu.com/p/c12fae498975 Ionic 项目开发完成之后呢,自然就是打包发布了,今天说说 iOS 的打包和发布.iOS 的发布方式分为三种:iOS ...

  9. SQL 事务隔离学习

    select --* request_session_id as spid, resource_type as restype, resource_database_id as dbid, DB_NA ...

  10. 交换ctrl和caps_loack的新方法

    交换ctrl和caps_loack的新方法 Table of Contents 1 过程 1 过程 debian用了几年,由于emacs的关系,一直将右ctrl和caps_lock键交换,使用的是xm ...