工具类封装如下:

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. shell随笔

    一, case的详细用法:   参考文章(http://blog.csdn.net/dreamtdp/article/details/8048720) 语句实例:由用户从键盘输入一个字符,并判断该字符 ...

  2. leetcode83

    /** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNo ...

  3. leetcode453

    public class Solution { public int MinMoves(int[] nums) { var list = nums.OrderBy(x => x).ToList( ...

  4. cookie和session的比较

    cookie和session的比较 一.对于cookie: ①cookie是创建于服务器端 ②cookie保存在浏览器端 ③cookie的生命周期可以通过cookie.setMaxAge(2000); ...

  5. 使用REGINI修改注册表权限

    regini regset.ini 就行啦 regset.ini 是你要修改的数据 1.注册表修改 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Curr ...

  6. Spring MVC 异常处理 - DefaultHandlerExceptionResolver

    对一些特殊的异常进行处理,比如方法类型不匹配, 转换错误.

  7. 13 python logging模块

    原文:http://www.cnblogs.com/dahu-daqing/p/7040764.html 1 logging模块简介 logging模块是Python内置的标准模块,主要用于输出运行日 ...

  8. Qt 信号槽

    Qt4与Qt5的信号槽有些不同: 1. Qt4的槽函数必须使用slots关键字声明,而Qt5中已经不再需要了,槽函数可以是任何能和信号关联的成员函数. 2. Qt4指定信号函数和槽函数需用SIGNAL ...

  9. python 升级到python2.7

    查看python的版本 [root@localhost ~] python  -V   Python 2.4.3 1.先安装GCC yum -y install gcc 如果安装gcc 出错, yum ...

  10. bash: ifconfig: command not found 问题解决

    ifconfig使用出现问题了?竟然提示找不到~~于是百度~~ [flymouse@localhost /]$ ifconfig 提示:“bash: ifconfig: command not fou ...