工具类封装如下:

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请求以及携带数据上传文件的更多相关文章

  1. Android 发送HTTP GET POST 请求以及通过 MultipartEntityBuilder 上传文件(二)

    Android 发送HTTP GET POST 请求以及通过 MultipartEntityBuilder 上传文件第二版 上次粗略的写了相同功能的代码,这次整理修复了之前的一些BUG,结构也大量修改 ...

  2. Android 发送HTTP GET POST 请求以及通过 MultipartEntityBuilder 上传文件

    折腾了好几天的 HTTP 终于搞定了,经测试正常,不过是初步用例测试用的,因为后面还要修改先把当前版本保存在博客里吧. 其中POST因为涉及多段上传需要导入两个包文件,我用的是最新的 httpmine ...

  3. python发送post请求上传文件,无法解析上传的文件

    前言 近日,在做接口测试时遇到一个奇葩的问题. 使用post请求直接通过接口上传文件,无法识别文件. 遇到的问题 以下是抓包得到的信息: 以上请求是通过Postman直接发送请求的. 在这里可以看到消 ...

  4. HttpClient通过Post上传文件(转)

    在之前一段的项目中,使用Java模仿Http Post方式发送参数以及文件,单纯的传递参数或者文件可以使用URLConnection进行相应的处理. 但是项目中涉及到既要传递普通参数,也要传递多个文件 ...

  5. 转 Android网络编程之使用HttpClient批量上传文件 MultipartEntityBuilder

    请尊重他人的劳动成果,转载请注明出处:Android网络编程之使用HttpClient批量上传文件 http://www.tuicool.com/articles/Y7reYb 我曾在<Andr ...

  6. HttpClient MultipartEntityBuilder 上传文件

    文章转载自: http://blog.csdn.net/yan8024/article/details/46531901 http://www.51testing.com/html/56/n-3707 ...

  7. [转]httpclient 上传文件、下载文件

    用httpclient4.3 post方式推送文件到服务端  准备:httpclient-4.3.3.jar:httpcore-4.3.2.jar:httpmime-4.3.3.jar/** * 上传 ...

  8. Java使用HttpClient上传文件

    Java可以使用HttpClient发送Http请求.上传文件等,非常的方便 Maven <dependency> <groupId>org.apache.httpcompon ...

  9. .Net使用HttpClient以multipart/form-data形式post上传文件及其相关参数

    前言: 本次要讲的是使用.Net HttpClient拼接multipark/form-data形式post上传文件和相关参数,并接收到上传文件成功后返回过来的结果(图片地址,和是否成功).可能有很多 ...

随机推荐

  1. 0_Simple__simpleStreams

    对比使用单流和多流(4条)情况下数据拷贝,以及数据拷贝加内核调用的效率差别.▶ 源代码 #include <stdio.h> #include <cuda_runtime.h> ...

  2. 谈谈 Python 程序的运行原理

    因为我的个人网站 restran.net 已经启用,博客园的内容已经不再更新.请访问我的个人网站获取这篇文章的最新内容,谈谈 Python 程序的运行原理 这篇文章准确说是『Python 源码剖析』的 ...

  3. Springboot spring data jpa 多数据源的配置01

    Springboot spring data jpa 多数据源的配置 (说明:这只是引入了多个数据源,他们各自管理各自的事务,并没有实现统一的事务控制) 例: user数据库   global 数据库 ...

  4. leetcode345

    public class Solution { public string ReverseVowels(string s) { var str = s.ToList(); var Vowels = n ...

  5. c++builder XE6 Remote Debuger 远程调试

    1.远程目标机器 安装D:\Program Files (x86)\Borland\Remote Debugger\20,没有光盘从已安装的xe6电脑上Bin目录下拷贝文件 bccide.dll bo ...

  6. keras图像预处理-ImageDataGenerator

    相关参数描述:http://keras-cn.readthedocs.io/en/latest/preprocessing/image/其中validation_split参数(官方上使用方法未描述) ...

  7. 简单AOP

    代码如下 //使用说明 //1,新加接口与类 //2,新加类并实现ICallHandler类: ExecuteHandler //3,新建特性并实现HandlerAttribute和重写其中的Crea ...

  8. SpringDataJPA模糊查询遇到的坑

    遇到的情况:在做短信渠道管理添加时,先要去校验数据库中是否有该产线-短信类型-渠道的记录,如果存在就不添加. //在库中是否存在该记录 private boolean ifExistChannelCo ...

  9. 开启mongod服务(Mongo运行错误:Failed to connect 127.0.0.1:27017,reason:errno:10061由于目标计算机积极拒绝,无法连接)

    问题:Mongo运行错误:Failed to connect 127.0.0.1:27017,reason:errno:10061由于目标计算机积极拒绝,无法连接 在Mongodb的安装过程中碰到的问 ...

  10. jquery 不选择第一个

    参考 https://zhidao.baidu.com/question/174343639.html th:not(':first')