HttpClient4.5.2调用示例(转载+原创)
操作HttpClient时的一个工具类,使用是HttpClient4.5.2
- package com.xxxx.charactercheck.utils;
- import java.io.File;
- import java.io.IOException;
- import java.net.URL;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
- import org.apache.http.HttpEntity;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.config.RequestConfig;
- 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.conn.ssl.DefaultHostnameVerifier;
- import org.apache.http.conn.util.PublicSuffixMatcher;
- import org.apache.http.conn.util.PublicSuffixMatcherLoader;
- import org.apache.http.entity.ContentType;
- import org.apache.http.entity.StringEntity;
- import org.apache.http.entity.mime.MultipartEntityBuilder;
- import org.apache.http.entity.mime.content.FileBody;
- import org.apache.http.entity.mime.content.StringBody;
- import org.apache.http.impl.client.CloseableHttpClient;
- import org.apache.http.impl.client.HttpClients;
- import org.apache.http.message.BasicNameValuePair;
- import org.apache.http.util.EntityUtils;
- public class HttpClientUtil {
- private RequestConfig requestConfig = RequestConfig.custom()
- .setSocketTimeout(15000)
- .setConnectTimeout(15000)
- .setConnectionRequestTimeout(15000)
- .build();
- private static HttpClientUtil instance = null;
- private HttpClientUtil(){}
- public static HttpClientUtil getInstance(){
- if (instance == null) {
- instance = new HttpClientUtil();
- }
- return instance;
- }
- /**
- * 发送 post请求
- * @param httpUrl 地址
- */
- public String sendHttpPost(String httpUrl) {
- HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
- return sendHttpPost(httpPost);
- }
- /**
- * 发送 post请求
- * @param httpUrl 地址
- * @param params 参数(格式:key1=value1&key2=value2)
- */
- public String sendHttpPost(String httpUrl, String params) {
- HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
- try {
- //设置参数
- StringEntity stringEntity = new StringEntity(params, "UTF-8");
- stringEntity.setContentType("application/x-www-form-urlencoded");
- httpPost.setEntity(stringEntity);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return sendHttpPost(httpPost);
- }
- /**
- * 发送 post请求
- * @param httpUrl 地址
- * @param maps 参数
- */
- public String sendHttpPost(String httpUrl, Map<String, String> maps) {
- HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
- // 创建参数队列
- List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
- for (String key : maps.keySet()) {
- nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
- }
- try {
- httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
- } catch (Exception e) {
- e.printStackTrace();
- }
- return sendHttpPost(httpPost);
- }
- /**
- * 发送 post请求(带文件)
- * @param httpUrl 地址
- * @param maps 参数
- * @param fileLists 附件
- */
- public String sendHttpPost(String httpUrl, Map<String, String> maps, List<File> fileLists) {
- HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
- MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
- for (String key : maps.keySet()) {
- meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN));
- }
- for(File file : fileLists) {
- FileBody fileBody = new FileBody(file);
- meBuilder.addPart("files", fileBody);
- }
- HttpEntity reqEntity = meBuilder.build();
- httpPost.setEntity(reqEntity);
- return sendHttpPost(httpPost);
- }
- /**
- * 发送Post请求
- * @param httpPost
- * @return
- */
- private String sendHttpPost(HttpPost httpPost) {
- CloseableHttpClient httpClient = null;
- CloseableHttpResponse response = null;
- HttpEntity entity = null;
- String responseContent = null;
- try {
- // 创建默认的httpClient实例.
- httpClient = HttpClients.createDefault();
- httpPost.setConfig(requestConfig);
- // 执行请求
- response = httpClient.execute(httpPost);
- entity = response.getEntity();
- responseContent = EntityUtils.toString(entity, "UTF-8");
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- // 关闭连接,释放资源
- if (response != null) {
- response.close();
- }
- if (httpClient != null) {
- httpClient.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return responseContent;
- }
- /**
- * 发送 get请求
- * @param httpUrl
- */
- public String sendHttpGet(String httpUrl) {
- HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
- return sendHttpGet(httpGet);
- }
- /**
- * 发送 get请求Https
- * @param httpUrl
- */
- public String sendHttpsGet(String httpUrl) {
- HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
- return sendHttpsGet(httpGet);
- }
- /**
- * 发送Get请求
- * @param httpPost
- * @return
- */
- private String sendHttpGet(HttpGet httpGet) {
- CloseableHttpClient httpClient = null;
- CloseableHttpResponse response = null;
- HttpEntity entity = null;
- String responseContent = null;
- try {
- // 创建默认的httpClient实例.
- httpClient = HttpClients.createDefault();
- httpGet.setConfig(requestConfig);
- // 执行请求
- response = httpClient.execute(httpGet);
- entity = response.getEntity();
- responseContent = EntityUtils.toString(entity, "UTF-8");
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- // 关闭连接,释放资源
- if (response != null) {
- response.close();
- }
- if (httpClient != null) {
- httpClient.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return responseContent;
- }
- /**
- * 发送Get请求Https
- * @param httpPost
- * @return
- */
- private String sendHttpsGet(HttpGet httpGet) {
- CloseableHttpClient httpClient = null;
- CloseableHttpResponse response = null;
- HttpEntity entity = null;
- String responseContent = null;
- try {
- // 创建默认的httpClient实例.
- PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString()));
- DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
- httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
- httpGet.setConfig(requestConfig);
- // 执行请求
- response = httpClient.execute(httpGet);
- entity = response.getEntity();
- responseContent = EntityUtils.toString(entity, "UTF-8");
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- // 关闭连接,释放资源
- if (response != null) {
- response.close();
- }
- if (httpClient != null) {
- httpClient.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return responseContent;
- }
- }
调用例子
- @ResponseBody
- @RequestMapping(value = "/check")
- public String check(
- Model model,
- HttpServletRequest request,
- HttpServletResponse response,
- String content) {
- try {
- String httpUrl = ExtendedServerConfig.getInstance().getStringProperty("httpUrl");
- Map<String, String> maps = new HashMap<String, String>();
- maps.put("content", content);
- maps.put("reserve_tag", ExtendedServerConfig.getInstance().getStringProperty("reserve_tag"));
- maps.put("user_key", ExtendedServerConfig.getInstance().getStringProperty("user_key"));
- maps.put("check_level", ExtendedServerConfig.getInstance().getStringProperty("check_level"));
- return HttpClientUtil.getInstance().sendHttpPost(httpUrl, maps);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
HttpClient4.5.2调用示例(转载+原创)的更多相关文章
- [转载+原创]Emgu CV on C# (三) —— Emgu CV on 均衡化
本文简要描述了均衡化原理及数学实现等理论问题,最终利用emgucv实现图像的灰度均衡. 直方图的均衡化,这是图像增强的常用方法. 一.均衡化原理及数学实现(转载) 均衡化原理及数学实现可重点参看——& ...
- 股票数据调用示例代码php
<!--?php // +---------------------------------------------------------------------- // | JuhePHP ...
- Nginx 简单的负载均衡配置示例(转载)
原文地址:Nginx 简单的负载均衡配置示例(转载) 作者:水中游于 www.s135.com 和 blog.s135.com 域名均指向 Nginx 所在的服务器IP. 用户访问http://www ...
- WebService核心文件【server-config.wsdd】详解及调用示例
WebService核心文件[server-config.wsdd]详解及调用示例 作者:Vashon 一.准备工作 导入需要的jar包: 二.配置web.xml 在web工程的web.xml中添加如 ...
- Windows API 调用示例
Ø 简介 本文主要记录 Windows API 的调用示例,因为这项技术并不常用,属于 C# 中比较孤僻或接触底层的技术,并不常用.但是有时候也可以借助他完成一些 C# 本身不能完成的功能,例如:通 ...
- C#中异步调用示例与详解
using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServi ...
- HTML 百度地图API调用示例源码
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...
- C#全能数据库操作类及调用示例
C#全能数据库操作类及调用示例 using System; using System.Data; using System.Data.Common; using System.Configuratio ...
- 利用JavaScriptSOAPClient直接调用webService --完整的前后台配置与调用示例
JavaScriptSoapClient下载地址:https://archive.codeplex.com/?p=javascriptsoapclient JavaScriptSoapClient的D ...
随机推荐
- Java Servlet 笔记1
1. 什么是Servlet. Java Servlet 是运行在 Web 服务器或应用服务器上的程序,它是作为来自 Web 浏览器或其他 HTTP 客户端的请求和 HTTP 服务器上的数据库或应用程序 ...
- Linux下安装3.0以上的python
Linux下自带的python2.7是不建议删除的,很多系统软件依赖python2.7,但是现在我们学习python一般需要python3.0,下面介绍安装python3.0. 1.进入python官 ...
- 第一次C语言作业
1. 求圆的面积和周长 输入圆的半径,求圆的周长和面积 流程图 测试结果: 实验问题:1.加号输入到引号内部导致运算终止 解决办法:通过改正加号位置是算法正确并继续运行 2判断闰年 输入一个四位年份, ...
- Mac下安装PEAR
The following instructions install PEAR and PECL on Mac OS X under/usr/local/. PECL is bundled with ...
- jQuery 遍历 – 祖先
祖先是父.祖父或曾祖父等等. 通过 jQuery,您能够向上遍历 DOM 树,以查找元素的祖先. 向上遍历 DOM 树 这些 jQuery 方法很有用,它们用于向上遍历 DOM 树: parent() ...
- 记一个万金油开源框架JHipster
本文地址:http://blog.csdn.net/sushengmiyan/article/details/53190236 百搭代码生成框架 体验新技术汇总: Spring Boot Spring ...
- java http post tomcat解除 长度限制
1. Get方法长度限制 Http Get方法提交的数据大小长度并没有限制,HTTP协议规范没有对URL长度进行限制.这个限制是特定的浏览器及服务器对它的限制. 如:IE对URL长度的限制是20 ...
- SQL Server 虚拟化(1)——虚拟化简介
本文属于SQL Server虚拟化系列 前言: 现代系统中,虚拟化越来越普遍,如果缺乏对虚拟化工作原理的理解,那么DBA在解决性能问题比如降低资源争用.提高备份还原速度等操作时就会出现盲点.所以基于本 ...
- ubuntu初始化python3+postgresql+uwsgi+nginx+django
一. postgresql 数据库 安装 apt-get update apt-get install postgresql 进入psql客户端 sudo -u postgres psql 创建数据库 ...
- Apache ActiveMQ实战(2)-集群
ActiveMQ的集群 内嵌代理所引发的问题: 消息过载 管理混乱 如何解决这些问题--集群的两种方式: Master slave Broker clusters ActiveMQ的集群有两种方式: ...