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. Qt开发中的实用笔记一--xml,Qpainter,Delegate:

    因为开发环境不能联网,开发中用到有用的知识就记在word稳定中,不知不觉就记载了几十页,为避免笔记丢失,现在就一点点忘博客上搬,方便日后回顾! ---------------------------- ...

  2. Unity 脚本生命周期流程图

    渲染 OnPreCull: 在相机剔除场景之前调用此函数.相机可见的对象取决于剔除.OnPreCull 函数调用发生在剔除之前. OnBecameVisible/OnBecameInvisible:  ...

  3. mvc路由,mvc区域

    1.路由在进行匹配时,会默认匹配第一个路由信息 2.路由规则的{control}和{action}时不能改变的 3.路由规则可以中间字符可以随便定义,但是{control}和{action}必须使用一 ...

  4. golang,liteide设置 windows7(64)

    1.安转go的环境,exe安装包 2.下载liteide27.2.1 3.打开liteide开始开发,在里面添加gopath,无法读取windows里面的gopath设置,不知道什么原因,以管理员运行 ...

  5. python小知识点

    问题:求列表中每个元素的元素次方之和>>> a=[1,2,3,4]>>> k=len(a)第一种解法#    s=0#    for x in a:#        ...

  6. OC宏和常量

    1.通常常量的定义const放在最前面: 2.宏的定义 #define TAG_ID 101,注意:宏名称和值之间没有等号,宏定义的末尾也不需要分号

  7. [Spring MVC] - JSP + Freemarker视图解释器整合

    Spring MVC中如果只使用JSP做视图,可以使用下面这段即可解决: <!-- 视图解释类 --> <bean class="org.springframework.w ...

  8. Temporary-Post-Used-For-Style-Detection-Title-16761156

    Temporary-Post-Used-For-Style-Detection-Content-16761156 =-=-=-=-=Powered by Blogilo

  9. maven 记录

    1. Can't find parent:  工程中的pom.xml中定义的”project -> version”或者”parent project -> version”设置的不对导致 ...

  10. VS2010 AppCode文件夹问题

    在Web应用程序中不能通过右键项目-〉”添加“-〉”添加ASP.NET文件夹“方式添加 .因为Web应用程序中App_Code就不存在 .不过可以通过手动的方式创建,添加一个文件夹命名为App_Cod ...