工具类封装如下:

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. 网络软工个人作业4——Alpha阶段个人总结

    1.个人总结 (1) 类型 具体技能和面试问题 现在的回答 毕业时找工作 语言 拿手的语言 Java 软件实现 有没有在别人的代码基础上进行改进,你是怎么读懂别人的代码,你采取什么方法不影响原来的功能 ...

  2. Eclipse创建Maven-Web项目及解决 jre版本和web.xml版本问题

    eclipse maven-web有个蛋疼的问题,就是web版本很低. 且看别人是如何解决的:Eclipse创建Maven-Web项目及解决 jre版本和web.xml版本问题

  3. cb6xe7代码提示风格变化

  4. head 标签

    1.<meta - > <meta charset="UTF-8"> #utf-8字符编码 <meta http-equiv="Refres ...

  5. mongodb基础学习9-分片

    分片和复制集不同,复制集是多个实例存储相同的内容,而分片是将内容存储到不同的分片上,不同分片存储的数据不同 下面看看具体的操作: 先启动两个片的实例: 再启动configsvr,要加上configsv ...

  6. 程序员教程-11章-Java程序设计

    自己是学java的,先看第十一章java吧. 列出章节目录,便于自己回忆内容. 11.1 Java语言概述 1 Java语言的特点 2 Java开发环境 11.2 Java语言基础 11.2.1 基本 ...

  7. 在Linux Bash通过上下键快速查找历史命令

    在centos 7中 ~/.bashrc 或者Mac中的 ~/.bash_profile 中添加,然后source一下以下内容: if [[ $- == *i* ]] then bind '" ...

  8. python-淘宝信息定向爬取

    S是类似产品页数  bcoffset直流偏移. 有人在将偏移量:http://www.cnblogs.com/defineconst/p/6185396.html item.taobao.com/it ...

  9. 向数据库添加学生信息。存放在REQUEST对象里

    代码前几天已经发过了,但是程序一直还没运行出来,今天重新建立了一个数据库,才可以,下面补充上数据截图

  10. hibernate 1对1的关系

    hibernate 中1对1的关系分为外键关联和主键关联 外键关联: //多方 public class Students {                                     ...