一、HttpClient 简介

HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。Java后台使用httpclient主要目的是为了模拟客户端的请求。

2、HttpClient的请求类型

实现了所有的Http请求类型,相应的类为:HttpGet、HttpPost、HttpDelete、HttpPut

3、Http的使用流程

1)导包

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5</version>
</dependency>

2)创建连接所需要的配置信息

public class HttpClientConfig {

    static int httpConnectTimeout = 10000;//连接超时时间(单位毫秒)

    static int httpSocketTimeout = 10000;//socket读写超时时间(单位毫秒)

    static int httpMaxPoolSize = 100;

    static int httpMonitorInterval = 3000;

    static int httpIdelTimeout = 2000;

    public static int getHttpIdelTimeout() {
return httpIdelTimeout;
} public static int getHttpSocketTimeout() {
return httpSocketTimeout;
} public static int getHttpMaxPoolSize() {
return httpMaxPoolSize;
} public static int getHttpMonitorInterval() {
return httpMonitorInterval;
} public static int getHttpConnectTimeout() {
return httpConnectTimeout;
}
}

3)封装HttpClientUtils类--包括连接池的信息

public class HttpClientUtils {

    private final static Logger logger = Logger.getLogger(HttpClientUtils.class);
private static CloseableHttpClient httpClient;
private static PoolingHttpClientConnectionManager manager; // 连接池管理类
private static ScheduledExecutorService monitorExecutor; // 监控
private final static Object syncLock = new Object(); // 相当于线程锁,用于线程安全
private static final int CONNECT_TIMEOUT = HttpClientConfig.getHttpConnectTimeout();// 设置连接建立的超时时间为10s
private static final int SOCKET_TIMEOUT = HttpClientConfig.getHttpSocketTimeout();
private static final int MAX_CONN = HttpClientConfig.getHttpMaxPoolSize(); // 最大连接数
private static final int Max_PRE_ROUTE = HttpClientConfig.getHttpMaxPoolSize();
private static final int MAX_ROUTE = HttpClientConfig.getHttpMaxPoolSize(); /**
* 对http请求进行基本设置
*
* @param httpRequestBase
* http请求
*/
private static void setRequestConfig(HttpRequestBase httpRequestBase) {
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONNECT_TIMEOUT)
.setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpRequestBase.setConfig(requestConfig);
} public static CloseableHttpClient getHttpClient(String url) {
String hostName = url.split("/")[2];
// System.out.println(hostName);
int port = 80;
if (hostName.contains(":")) {
String[] args = hostName.split(":");
hostName = args[0];
port = Integer.parseInt(args[1]);
}
if (httpClient == null) {
// 多线程下多个线程同时调用getHttpClient容易导致重复创建httpClient对象的问题,所以加上了同步锁
synchronized (syncLock) {
if (httpClient == null) {
httpClient = createHttpClient(hostName, port);
// 开启监控线程,对异常和空闲线程进行关闭
monitorExecutor = Executors.newScheduledThreadPool(1);
monitorExecutor.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// 关闭异常连接
manager.closeExpiredConnections();
// 关闭5s空闲的连接
manager.closeIdleConnections(HttpClientConfig.getHttpIdelTimeout(), TimeUnit.MILLISECONDS);
logger.debug("close expired and idle for over 5s connection");
}
}, HttpClientConfig.getHttpMonitorInterval(), HttpClientConfig.getHttpMonitorInterval(),
TimeUnit.MILLISECONDS);
}
}
}
return httpClient;
} /**
* 根据host和port构建httpclient实例
*
* @param host
* 要访问的域名
* @param port
* 要访问的端口
* @return
*/
public static CloseableHttpClient createHttpClient(String host, int port) {
ConnectionSocketFactory plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory();
LayeredConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("http", plainSocketFactory).register("https", sslSocketFactory).build();
manager = new PoolingHttpClientConnectionManager(registry);
// 设置连接参数
manager.setMaxTotal(MAX_CONN); // 最大连接数
manager.setDefaultMaxPerRoute(Max_PRE_ROUTE); // 路由最大连接数
HttpHost httpHost = new HttpHost(host, port);
manager.setMaxPerRoute(new HttpRoute(httpHost), MAX_ROUTE);
// 请求失败时,进行请求重试
HttpRequestRetryHandler handler = new HttpRequestRetryHandler() {
@Override
public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
if (i > 3) {
// 重试超过3次,放弃请求
logger.error("retry has more than 3 time, give up request");
return false;
}
if (e instanceof NoHttpResponseException) {
// 服务器没有响应,可能是服务器断开了连接,应该重试
logger.error("receive no response from server, retry");
return true;
}
if (e instanceof SSLHandshakeException) {
// SSL握手异常
logger.error("SSL hand shake exception");
return false;
}
if (e instanceof InterruptedIOException) {
// 超时
logger.error("InterruptedIOException");
return false;
}
if (e instanceof UnknownHostException) {
// 服务器不可达
logger.error("server host unknown");
return false;
}
if (e instanceof ConnectTimeoutException) {
// 连接超时
logger.error("Connection Time out");
return false;
}
if (e instanceof SSLException) {
logger.error("SSLException");
return false;
}
HttpClientContext context = HttpClientContext.adapt(httpContext);
HttpRequest request = context.getRequest();
if (!(request instanceof HttpEntityEnclosingRequest)) {
// 如果请求不是关闭连接的请求
return true;
}
return false;
}
};
CloseableHttpClient client = HttpClients.custom().setConnectionManager(manager).setRetryHandler(handler)
.build();
return client;
} /**
* 关闭连接池
*/
public static void closeConnectionPool() {
try {
httpClient.close();
manager.close();
monitorExecutor.shutdown();
} catch (IOException e) {
e.printStackTrace();
}
} }
/**
* 对http请求进行基本设置
*
* @param httpRequestBase
* http请求
*/
private static void setRequestConfig(HttpRequestBase httpRequestBase) {
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONNECT_TIMEOUT)
.setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpRequestBase.setConfig(requestConfig);
}

4)form表单提交

    public static String doPostForm(String url, Map<String, String> params) {
HttpPost httpPost = new HttpPost(url);
setRequestConfig(httpPost);
String resultString = "";
CloseableHttpResponse response = null;
try { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); if (params != null) {
for (String key : params.keySet()) {
builder.addPart(key,
new StringBody(params.get(key), ContentType.create("text/plain", Consts.UTF_8)));
}
} HttpEntity reqEntity = builder.build();
httpPost.setEntity(reqEntity); // 发起请求 并返回请求的响应
response = getHttpClient(url).execute(httpPost, HttpClientContext.create());
resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null)
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}

5)File文件上传

    public static String uploadFile(String url, String localFile, String fileParamName, Map<String, String> params) {
HttpPost httpPost = new HttpPost(url);
setRequestConfig(httpPost);
String resultString = "";
CloseableHttpResponse response = null;
try {
// 把文件转换成流对象FileBody
FileBody bin = new FileBody(new File(localFile)); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); // 相当于<input type="file" name="file"/>
builder.addPart("files", bin);
// 相当于<input type="text" name="userName" value=userName>
builder.addPart("filesFileName",
new StringBody(fileParamName, ContentType.create("text/plain", Consts.UTF_8)));
if (params != null) {
for (String key : params.keySet()) {
builder.addPart(key,
new StringBody(params.get(key), ContentType.create("text/plain", Consts.UTF_8)));
}
} HttpEntity reqEntity = builder.build();
httpPost.setEntity(reqEntity); // 发起请求 并返回请求的响应
response = getHttpClient(url).execute(httpPost, HttpClientContext.create());
resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null)
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}

6) 传输Json数据

    public static String doPostJson(String url, String json) {
HttpPost httpPost = new HttpPost(url);
setRequestConfig(httpPost);
String resultString = "";
CloseableHttpResponse response = null;
try {
// 设置ContentType(注:如果只是传普通参数的话,ContentType不一定非要用application/json)
// httpPost.setHeader("Content-Type",
// "application/json;charset=utf8");
httpPost.setHeader("Content-Type", "application/json"); // 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = getHttpClient(url).execute(httpPost, HttpClientContext.create());
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
logger.error("httpclient的get请求失败,url:" + url, e);
// e.printStackTrace();
} finally {
try {
if (response != null)
response.close();
} catch (IOException e) {
logger.error("IOException的错误", e);
// e.printStackTrace();
}
}
return resultString;
}

欢迎关注微信公众号【Java典籍】,收看更多Java技术干货!关注即送java全套资料一份

   ▼微信扫一扫下图↓↓↓二维码关注

 

Java后台使用httpclient入门HttpPost请求(form表单提交,File文件上传和传输Json数据)的更多相关文章

  1. node07---post请求、表单提交、文件上传

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  2. JavaScript实现form表单的多文件上传

    form表单的多文件上传,具体内容如下 formData对象可以使用一系列的键值对来模拟一个完整的表单,然后使用Ajax来发送这个表单 使用<form>表单初始化FormData对象的方式 ...

  3. [Nginx 2] form表单提交,图片上传

    导读:昨晚恶补了一些Nginx服务器的东西,从整体上对Nginx有一个初步的了解.上午去找师哥问了问目前项目中的使用情况,然后就开始上传图片了.这里就简单总结整理一下今天的成果,以后接着提升.简单粗暴 ...

  4. (27) java web的struts2框架的使用-基于表单的多文件上传

    和单个文件上传配置都是一样的,只是在action中接受参数时候,接受的是数组,不再是单个的文件. 一,action的实现: public class MutableFilesUpload extend ...

  5. form表单系列中文件上传及预览

    文件上传及预览 Form提交 Ajax 上传文件 时机: 如果发送的[文件]:->iframe, jQurey(),伪Ajax 预览 import os img_path = os.path.j ...

  6. form表单提交file

    form表单提交文件,这毫无疑问不是个好办法.但是,存在既有意义.既然H5都还让着东西存在着,呢么必然有其意义. form表单中的input type=file这个空间,不得不说奇丑无比!问题是还不能 ...

  7. form表单提交的时候,传过去的值是键值对的形式

    效果展示 第一种需求,点击input的时候,input的value发生改变 $('.group-wrapper input').click(function(){ $(this).val(0); // ...

  8. 获取html 中的内容 将前台的数据获取到后台 用 jquery 生成一个 form表单 提交数据

    使用js创建一个form表单 ,使用post上传到后台中 下面是代码.在获取html内容的时候使用了js节点来获取内容. parent:父节点.上一级的节点 siblings:兄弟节点.同一级别的节点 ...

  9. form表单提交中文乱码(前台中文到JAVA后台乱码)问题及解决

    form表单提交中文乱码(前台中文到JAVA后台乱码)问题及解决 一.问题: 页面输入框中的中文内容,在后台乱码,导致搜索功能失效:(详细可以见后面的重现) 二.原因: 浏览器对于数据的默认编码格式为 ...

随机推荐

  1. 前端零基础入门:页面结构层HTML(2)

    学习笔记 若本号内容有做得不到位的地方(比如:涉及版权或其他问题),请及时联系我们进行整改即可,会在第一时间进行处理. 请点赞!因为你们的赞同/鼓励是我写作的最大动力! 欢迎关注达达的简书! 这是一个 ...

  2. js中实现函数防抖跟函数节流

    最近刚接触两个新概念函数防抖与函数节流,虽然这些内容网上可以搜到很多,大家都有自己的一套的理解方式,都写得很好, 而自己则想在理解的基础上自己把代码实现一遍,加深印象. 一.函数防抖 假如我们有这样的 ...

  3. System.NotSupportedException:“No data is available for encoding 1252. For information on defining a custom encoding

    最近搞 .net项目,Dapper连接Mysql时,运行报错: System.NotSupportedException:“No data is available for encoding 1252 ...

  4. 使用adb连接Mumu模拟器

    1)下载Mumu模拟器 2)运行Mumu模拟器 3)找到mumu安装目录下的MuMu\emulator\nemu\vmonitor\bin目录 4)在当前目录打开cmd,执行 adb connect ...

  5. KD-Tree总结

    KD-Tree总结 问题引入 平面上有\(n\)个点,\(q\)组询问,每一次查询距离\((x,y)\)最近的点对,强制在线. 问题解决 暴力 显然我们可以直接枚举点然后算距离取\(min\),这样子 ...

  6. 远程桌面无法连接 提示不支持FIPS安全级别的解决方法

    远程桌面可以通过网络连接到另一台电脑进行操作,可以方便在家操作公司电脑.但是到了这个新公司却出现了一个问题,提示客户端无法建立跟远程计算机的连接,我的天,要命了. 远程桌面无法连接错误提示 仔细一看说 ...

  7. 【Beta】设计与计划

    目录 新增功能描述 小程序:按模块说明需求 用户权限模块 新闻模块 活动模块 社团模块 社团管理模块 小程序:按页面说明需求变化 新闻页 活动页/活动列表页 活动详情页 社团页 某类别社团页 社团详情 ...

  8. vmware ubuntu16 启动蓝屏屏幕闪

    vmware ubuntu16 启动蓝屏屏幕闪 虚拟机安装了ubuntu16 desktop,没有关闭自动更新: 结果关机虚拟机时出现等5秒更新,类似win10关机更新: 再开机发现就蓝屏了,多次重启 ...

  9. easyui datagrid的editor编辑器如何为validatebox控件添加改变事件

    项目中需要为行编辑器Editor的某个列的文本框添加改变事件 需求:新增行时,为用户名输入特殊字符进行验证,不允许保存用户数据 html页面 <table id="gridlist&q ...

  10. essay sundry

    感觉很多单词, 即使是所谓的抽象名词都有复数形式,是习惯用法,比如, details, comments, ads等 ad: 广告, advertise的缩写? advertise. advertis ...