【httpclient-4.3.1.jar】httpclient发送get、post请求以及携带数据上传文件

工具类封装如下:
package cn.qlq.utils; import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set; import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
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.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; /**
* http工具类的使用
*
* @author Administrator
*
*/
public class HttpUtils { private static Logger logger = LoggerFactory.getLogger(HttpUtils.class); /**
* get请求
*
* @return
*/
public static String doGet(String url) {
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try {
// 定义HttpClient
client = HttpClientBuilder.create().build();
// 发送get请求
HttpGet request = new HttpGet(url);
// 执行请求
response = client.execute(request); return getResponseResult(response);
} catch (Exception e) {
logger.error("execute error,url: {}", url, e);
} finally {
IOUtils.closeQuietly(response);
IOUtils.closeQuietly(client);
} return "";
} /**
* get请求携带参数
*
* @return
*/
public static String doGetWithParams(String url, Map<String, String> params) {
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try {
// 定义HttpClient
client = HttpClientBuilder.create().build(); // 1.转化参数
if (params != null && params.size() > 0) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (Iterator<String> iter = params.keySet().iterator(); iter.hasNext();) {
String name = iter.next();
String value = params.get(name);
nvps.add(new BasicNameValuePair(name, value));
}
String paramsStr = EntityUtils.toString(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
url += "?" + paramsStr;
} HttpGet request = new HttpGet(url);
response = client.execute(request); return getResponseResult(response);
} catch (IOException e) {
logger.error("execute error,url: {}", url, e);
} finally {
IOUtils.closeQuietly(response);
IOUtils.closeQuietly(client);
} return "";
} public static String doPost(String url, Map<String, String> params) {
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try {
// 定义HttpClient
client = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(url); // 1.转化参数
if (params != null && params.size() > 0) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (Iterator<String> iter = params.keySet().iterator(); iter.hasNext();) {
String name = iter.next();
String value = params.get(name);
nvps.add(new BasicNameValuePair(name, value));
}
request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
} response = client.execute(request);
return getResponseResult(response);
} catch (IOException e) {
logger.error("execute error,url: {}", url, e);
} finally {
IOUtils.closeQuietly(response);
IOUtils.closeQuietly(client);
} return "";
} public static String doPost(String url, String params) {
return doPost(url, params, false);
} /**
* post请求(用于请求json格式的参数)
*
* @param url
* @param params
* @param isJsonData
* @return
*/
public static String doPost(String url, String params, boolean isJsonData) {
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try {
// 定义HttpClient
client = HttpClientBuilder.create().build(); HttpPost request = new HttpPost(url);
StringEntity entity = new StringEntity(params, HTTP.UTF_8);
request.setEntity(entity); if (isJsonData) {
request.setHeader("Accept", "application/json");
request.setHeader("Content-Type", "application/json");
} response = client.execute(request); return getResponseResult(response);
} catch (IOException e) {
logger.error("execute error,url: {}", url, e);
} finally {
IOUtils.closeQuietly(response);
IOUtils.closeQuietly(client);
} return "";
} /**
* 上传文件携带参数发送请求
*
* @param url
* URL
* @param fileName
* neme,相当于input的name
* @param filePath
* 本地路径
* @param params
* 参数
* @return
*/
public static String doPostWithFile(String url, String fileName, String filePath, Map<String, String> params) {
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
CloseableHttpResponse response = null;
try {
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); // 上传文件,如果不需要上传文件注掉此行
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE).addPart(fileName,
new FileBody(new File(filePath))); if (params != null && params.size() > 0) {
Set<Entry<String, String>> entrySet = params.entrySet();
for (Entry<String, String> entry : entrySet) {
multipartEntityBuilder.addTextBody(entry.getKey(), entry.getValue(),
ContentType.create(HTTP.PLAIN_TEXT_TYPE, StandardCharsets.UTF_8));
}
} HttpEntity httpEntity = multipartEntityBuilder.build(); HttpPost httppost = new HttpPost(url);
httppost.setEntity(httpEntity); response = httpclient.execute(httppost);
return getResponseResult(response);
} catch (Exception e) {
logger.error("execute error,url: {}", url, e);
} finally {
IOUtils.closeQuietly(response);
IOUtils.closeQuietly(httpclient);
} return "";
} private static String getResponseResult(CloseableHttpResponse response) throws ParseException, IOException {
/** 请求发送成功,并得到响应 **/
if (response != null) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(response.getEntity(), "utf-8");
} else {
logger.error("getResponseResult code error, code: {}", response.getStatusLine().getStatusCode());
}
} return "";
}
}
上述代码支持application/json数据的传送。post方法的isJsonData 为true即在请求头部加上application/json。
测试代码:
Controller层:
@RequestMapping("/test")
@ResponseBody
public String test(HttpServletRequest request, HttpServletResponse response) {
String method = request.getMethod();
System.out.println("========================");
System.out.println("request.getMethod(): " + method);
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String parameterName = (String) parameterNames.nextElement();
String parameterValue = request.getParameter(parameterName);
System.out.println(" parameterName: " + parameterName + " , parameterValue: " + parameterValue + " ");
}
return "success";
}
测试:
public static void main(String[] args) {
String doGet = doGet("http://localhost:8088//weixin/test/test.html?name=zs&age=25");
System.out.println(doGet);
Map<String, String> map = new HashMap<String, String>();
map.put("xx", "xxx");
String doGetWithParams = doGetWithParams("http://localhost:8088//weixin/test/test.html", map);
System.out.println(doGetWithParams);
String doPost = doPost("http://localhost:8088//weixin/test/test.html?name=zs&age=25", "");
System.out.println(doPost);
String doPost2 = doPost("http://localhost:8088//weixin/test/test.html?name=zs&age=25", map);
System.out.println(doPost2);
}
结果:
========================
request.getMethod(): GET
parameterName: name , parameterValue: zs
parameterName: age , parameterValue: 25
========================
request.getMethod(): GET
parameterName: xx , parameterValue: xxx
========================
request.getMethod(): POST
parameterName: name , parameterValue: zs
parameterName: age , parameterValue: 25
========================
request.getMethod(): POST
parameterName: name , parameterValue: zs
parameterName: age , parameterValue: 25
parameterName: xx , parameterValue: xxx
补充:NameValuePair是键值对的数据结构,内部维护一个key属性、一个value属性。有时候可替代map解决一些问题:
public interface NameValuePair {
String getName();
String getValue();
}
例如:
Map<String, String> params = new HashMap<>();
params.put("name", "zhangsan");
params.put("age", "25");
params.put("sex", "男");
params.put("network", "http://zhangsan.com"); List<NameValuePair> nameValuePairs = new LinkedList<>();
for (Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); iterator.hasNext();) {
Entry<String, String> next = iterator.next();
String key = next.getKey();
String value = next.getValue();
nameValuePairs.add(new BasicNameValuePair(key, value));
}
String string = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs));
System.out.println(string); // URLEncodedUtils工具类使用
System.out.println("========URLEncodedUtils编码解码======");
String format = URLEncodedUtils.format(nameValuePairs, StandardCharsets.UTF_8);
System.out.println(format); List<NameValuePair> parse = URLEncodedUtils.parse(format, StandardCharsets.UTF_8);
System.out.println(parse);
结果:
sex=%3F&age=25&name=zhangsan&network=http%3A%2F%2Fzhangsan.com
========URLEncodedUtils编码解码======
sex=%E7%94%B7&age=25&name=zhangsan&network=http%3A%2F%2Fzhangsan.com
[sex=男, age=25, name=zhangsan, network=http://zhangsan.com]
【httpclient-4.3.1.jar】httpclient发送get、post请求以及携带数据上传文件的更多相关文章
- Android 发送HTTP GET POST 请求以及通过 MultipartEntityBuilder 上传文件(二)
Android 发送HTTP GET POST 请求以及通过 MultipartEntityBuilder 上传文件第二版 上次粗略的写了相同功能的代码,这次整理修复了之前的一些BUG,结构也大量修改 ...
- Android 发送HTTP GET POST 请求以及通过 MultipartEntityBuilder 上传文件
折腾了好几天的 HTTP 终于搞定了,经测试正常,不过是初步用例测试用的,因为后面还要修改先把当前版本保存在博客里吧. 其中POST因为涉及多段上传需要导入两个包文件,我用的是最新的 httpmine ...
- python发送post请求上传文件,无法解析上传的文件
前言 近日,在做接口测试时遇到一个奇葩的问题. 使用post请求直接通过接口上传文件,无法识别文件. 遇到的问题 以下是抓包得到的信息: 以上请求是通过Postman直接发送请求的. 在这里可以看到消 ...
- HttpClient通过Post上传文件(转)
在之前一段的项目中,使用Java模仿Http Post方式发送参数以及文件,单纯的传递参数或者文件可以使用URLConnection进行相应的处理. 但是项目中涉及到既要传递普通参数,也要传递多个文件 ...
- 转 Android网络编程之使用HttpClient批量上传文件 MultipartEntityBuilder
请尊重他人的劳动成果,转载请注明出处:Android网络编程之使用HttpClient批量上传文件 http://www.tuicool.com/articles/Y7reYb 我曾在<Andr ...
- HttpClient MultipartEntityBuilder 上传文件
文章转载自: http://blog.csdn.net/yan8024/article/details/46531901 http://www.51testing.com/html/56/n-3707 ...
- [转]httpclient 上传文件、下载文件
用httpclient4.3 post方式推送文件到服务端 准备:httpclient-4.3.3.jar:httpcore-4.3.2.jar:httpmime-4.3.3.jar/** * 上传 ...
- Java使用HttpClient上传文件
Java可以使用HttpClient发送Http请求.上传文件等,非常的方便 Maven <dependency> <groupId>org.apache.httpcompon ...
- .Net使用HttpClient以multipart/form-data形式post上传文件及其相关参数
前言: 本次要讲的是使用.Net HttpClient拼接multipark/form-data形式post上传文件和相关参数,并接收到上传文件成功后返回过来的结果(图片地址,和是否成功).可能有很多 ...
随机推荐
- OpenCL 存储器次序的验证
▶ <OpenCL异构并行编程实战>P224 的代码,先放上来,坐等新设备到了再执行 //kernel.cl __global ); // 全局原子对象 __kernel void mem ...
- 26. 天马tomcat授权文件的影响因素
问题:Tianma版本同一台机器的Server端序列号有时会显示空白 描述:同一台机器的tomcat,tianma版本序列号为空(如图) 解决:手动删除ABS_DOCUMENT\LiveBos目录下s ...
- as3 代码优化
1 代码写法 1 定义局部变量 定义局部变量的时候,一定要用关键字var来定义,因为在Flash播放器中,局部变量的运行速度更快,而且在他们的作用域外是不耗占系统资源的.当一个函数调用结束的时候,相应 ...
- UI5-文档-导航栏
UI5-文档-1-前言 UI5-文档-2-开发环境 UI5-文档-2.1-使用OpenUI5开发应用 UI5-文档-2.2-使用SAP Web IDE开发应用程序 UI5-文档-2.3-使用SAPUI ...
- app.$mount("#app") 手动挂载
$mount()手动挂载 当Vue实例没有el属性时,则该实例尚没有挂载到某个dom中: 假如需要延迟挂载,可以在之后手动调用vm.$mount()方法来挂载.例如: new Vue({ //el: ...
- tair介绍以及配置
简介 tair 是淘宝自己开发的一个分布式 key/value 存储引擎. tair 分为持久化和非持久化两种使用方式. 非持久化的 tair 可以看成是一个分布式缓存. 持久化的 tair 将数据存 ...
- mysql 变量名称不能与表字段一致
my sql的变量名称不能与表字段名称相同不然会有各种异常问题 啃爹
- 判断一个对象是否为真 __nonzero__ 方法和 __len__方法
class A(): def __nonzero__(self): # 判断 一个对象是否为空,先查看该方法的返回值 return 1 def __len__(self): # 如果没有上一个方法,那 ...
- 实现Action的三种方式
实现Action的三种方式: 1.普通类 一般采用此种方法 2.实现Action接口 3.继承ActionSupport类
- Maven常用命令及Eclipse应用
一般来说,github上大多的java项目都是使用maven,ant等进行构建的.由于之前没有使用过maven,因此这几天对maven进行了简单的学习.古话说:“温故而知新”,一些命令长时间不使用都会 ...