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 ...
随机推荐
- bzoj2434阿狸的自动机
转载自 http://www.cnblogs.com/zj75211/p/6934976.html ●BZOJ 2434: [Noi2011]阿狸的打字机 ●赘述题目 (题意就不赘述了) ●解法: ...
- 百度杯CTF夺旗大赛9月场writeup
在i春秋上注册了账号,准备业余时间玩玩CTF.其中的九月场已经打完了,但是不妨碍我去做做题,现在将一些思路分享一下. 一. 第二场web SQL 根据题目来看是一个SQL注入的题目: 这里推荐两篇文章 ...
- 【docker简易笔记】docker基础信息的分享
docker 使用的频率越来越高,所以在后续的一些博客中会分享一些docker的安装和使用. 一.docker介绍 "Docker 最初是 dotCloud 公司创始人 Solomon ...
- CentOS7 下安装 Java 8 [wget]
1. 创建一个文件夹 sudo mkdir /usr/local/services/java8 2. 使用 wget 来下载 wget --no-cookies --no-check-certific ...
- JAVA NIO工作原理及代码示例
简介:本文主要介绍了JAVA NIO中的Buffer, Channel, Selector的工作原理以及使用它们的若干注意事项,最后是利用它们实现服务器和客户端通信的代码实例. 欢迎探讨,如有错误敬请 ...
- postgresql 安装使用
www.postgresql.org去下载你需要的版本,我下载的9.6.8 安装过程中会让你输入一次密码,其余的默认就ok 默认超级用户名postgres 打开 pgadmin4,我们将语言改为中文会 ...
- Elasticsearch 学习(一):入门
一.概念 Elasticsearch 是一个实时分布式搜索和分析引擎.它用于全文搜索.结构化搜索.分析以及将这三者混合使用. 维基百科.英国卫报.StackOverflow.Github 等公司都在使 ...
- ajax中基本参数应用
$(function () { $("#verificationCodeBtn").click(function () { $("#verificationCodeIma ...
- js简单备忘录
<section class="myMemory"> <h3 class="f-tit">记事本</h3> <div ...
- MongoDB 查询文档
语法 MongoDB 查询数据的语法格式如下: >db.COLLECTION_NAME.find() find() 方法以非结构化的方式来显示所有文档. 如果你需要以易读的方式来读取数据,可以使 ...