一、HttpClient

HttpClient是Apache HttpComponents 下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包(httpclient-4.4.1.jar)。HttpClient类可以用来发送Http请求(get,post,put,delete)相比传统JDK自带的URLConnection,增加了易用性和灵活性,如下为一个post类型的HTTP请求,参数列表中的header代表HTTP请求的header,params代表参数列表,body代表HTTP请求体

需要导入:import org.apache.http.client.HttpClients等
    public String post(String url,Map<String, String> header, Map<String, Object> params, Map<String, Object> entity, int soTimeout) {
CloseableHttpClient httpclient = HttpClients.createDefault(); //创建一个httpclient
HttpPost httppost = new HttpPost(); //创建一个httppost
String result = null;
try {
//处理params,拼接url
url = joinParam(url, params); //根据需求自己实现该方法 //add request url
if (url != null) {
httppost.setURI(URI.create(url));
} //add header
for (String key : header.keySet()) {
httppost.addHeader(key, header.get(key));
} //add entity
if (entity != null) {
String entityStr = toJSONString(entity); //将map转化为string
StringEntity stringEntity = new StringEntity(entityStr, "UTF-8");
stringEntity.setContentType("text/json");
stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(stringEntity);
}
/**
* setConnectTimeout:设置连接超时时间,单位毫秒。
*setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
*setSocketTimeout:请求获取数据的超时时间,单位毫秒。
*/
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(soTimeout).setConnectionRequestTimeout(soTimeout)
.setSocketTimeout(soTimeout).build();
httppost.setConfig(requestConfig); CloseableHttpResponse response = null;
try {
//发送post请求
response = httpclient.execute(httppost);
} catch (IOException e) {
e.printStackTrace();
}
try {
// 获取响post响应实体
if (response != null) {
HttpEntity responseEntity = response.getEntity();
if(responseEntity != null) {
result = responseEntity.toString();
if(responseEntity != null) {
result = EntityUtils.toString(responseEntity);
}
}
}
} finally {
if (response != null) {
response.close();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}

二、老版本HttpClient(commons-httpclient.jar)

进入apache官网下找commons HttpClient包,可以看到一下描述:

The Commons HttpClient project is now end of life, and is no longer being developed. It has been replaced by the Apache HttpComponents project in its HttpClient and HttpCore modules, which offer better performance and more flexibility.

可以看到commons-httpclient.jar已被httpclient.jar取代,官方不再提供commons-httpclient的更新维护服务。以下是使用老版本HttpClient发送一个post请求:

需要导入:import org.apache.commons.httpclient.HttpClient等

    public String doPost(String url, Map<String, String> header, Map<String, Object> entity){
String result = "";
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(url);
try{
//set header
postMethod.addRequestHeader("Content-Type", "application/json");
for (String key : header.keySet()) {
postMethod.addRequestHeader(key, header.get(key));
} //set entity
String paramsStr = toJSONString(entity);
RequestEntity requestEntity = new ByteArrayRequestEntity(paramsStr.getBytes("UTF-8"));
postMethod.setRequestEntity(requestEntity); //get response
int httpStatusCode = httpClient.executeMethod(postMethod);
if (httpStatusCode < 200 || httpStatusCode >= 300) {
throw new Exception("httpStatusCode is not correct! " + httpStatusCode);
}
result = IOUtils.toString(postMethod.getResponseBodyAsStream(), "UTF-8");
}catch (Exception e){
e.printStackTrace();
}finally {
postMethod.releaseConnection();
}
return result;
}

HttpClient基础用法的更多相关文章

  1. PropertyGrid控件由浅入深(二):基础用法

    目录 PropertyGrid控件由浅入深(一):文章大纲 PropertyGrid控件由浅入深(二):基础用法 控件的外观构成 控件的外观构成如下图所示: PropertyGrid控件包含以下几个要 ...

  2. logstash安装与基础用法

    若是搭建elk,建议先安装好elasticsearch 来自官网,版本为2.3 wget -c https://download.elastic.co/logstash/logstash/packag ...

  3. elasticsearch安装与基础用法

    来自官网,版本为2.3 注意elasticsearch依赖jdk,2.3依赖jdk7 下载rpm包并安装 wget -c https://download.elastic.co/elasticsear ...

  4. BigDecimal最基础用法

    BigDecimal最基础用法 用字符串生成的BigDecimal是不会丢精度的. 简单除法. public class DemoBigDecimal { public static void mai ...

  5. Vue组件基础用法

    前面的话 组件(Component)是Vue.js最强大的功能之一.组件可以扩展HTML元素,封装可重用的代码.根据项目需求,抽象出一些组件,每个组件里包含了展现.功能和样式.每个页面,根据自己所需, ...

  6. Smarty基础用法

    一.Smarty基础用法: 1.基础用法如下 include './smarty/Smarty.class.php';//引入smarty类 $smarty = new Smarty();//实例化s ...

  7. 前端自动化测试神器-Katalon的基础用法

    前言 最近由于在工作中需要通过Web端的功能进行一次大批量的操作,数据量大概在5000左右,如果手动处理, 完成一条数据的操作用时在20秒左右的话,大概需要4-5个人/天的工作量(假设一天8小时的工作 ...

  8. Bootstrap fileinput:文件上传插件的基础用法

    官网地址:http://plugins.krajee.com/ 官网提供的样例:http://plugins.krajee.com/file-input/demo 基础用法一 导入核心CSS及JS文件 ...

  9. asyncio 基础用法

    asyncio 基础用法 python也是在python 3.4中引入了协程的概念.也通过这次整理更加深刻理解这个模块的使用 asyncio 是干什么的? asyncio是Python 3.4版本引入 ...

随机推荐

  1. 在IE中MVC控制器中返回JSON格式的数据时提示下载

    最近做项目时,视图中用jquery.form.js异步提交表单时,接收的是JSON格式的数据,但是奇怪的是在IE中提示下载文件,其他浏览器中一切正常,下载后,里面的内容就是在控制器中返回的数据.代码如 ...

  2. vue.js 源代码学习笔记 ----- core scedule.js

    /* @flow */ import type Watcher from './watcher' import config from '../config' import { callHook } ...

  3. easyUI---分页插件

    设置 //分页组件 $('#detailLayer .detailPag').pagination({ pageNumber: 1, pageSize: 10, total: result.Total ...

  4. [Scala]Scala学习笔记五 Object

    1. 单例对象 Scala没有静态方法或静态字段,可以使用object来达到这个目的,对象定义了某个类的单个实例: object Account{ private var lastNumber = 0 ...

  5. Nginx 作为反向代理优化要点proxy_buffering

    当nginx用于反向代理时,每个客户端将使用两个连接:一个用于响应客户端的请求,另一个用于到后端的访问: 那么,可以从如下配置起步: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ...

  6. ios 10.3下载 Xcode8配置支持 ios 10.3下载

    一不小心,手机又升级了,哎

  7. 6.二元查找树的后序遍历结果[PostOrderOfBST]

    [题目] 输入一个整数数组,判断该数组是不是某二元查找树的后序遍历的结果.如果是返回true,否则返回false. 例如输入5.7.6.9.11.10.8,由于这一整数序列是如下树的后序遍历结果: 8 ...

  8. learn go passing variable-length arguments

    package main // 参考文档: // https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/06.3.md im ...

  9. 【剑指offer】二叉树的镜像,C++实现(先序遍历)

    原创博文,转载请注明出处!github地址  博客文章索引地址 1.题目       输入一颗二叉树,将二叉树变换为原二叉树的镜像,如下图所示: 2.思路 二叉树有0个节点 二叉树有1个节点 二叉树有 ...

  10. 【集成学习】安装lightgbm

    1.下载whl lightgbm的whl下载地址 2.输入命令 pip install lightgbm-2.0.3-py2.py3-one-win_am64.whl 3.验证是否成功 import ...