工具类封装如下:

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. JS吧数字转成2进制 8进制16进制数据

    ; number.toString(); //转成2进制 number.toString();//转成8进制 number.toString();//转成10进制 number.toString(); ...

  2. 队列queue实例(生产者和消费者模型)

    import queue, threading, time q = queue.Queue(maxsize=10)def producter(n): count = 1 while True: q.p ...

  3. Star打印机数据解密

    通过串口调试工具 抓取到的16进制文本; 如下 然后打开我们的文档,查看命令数据内容. 详情请密我QQ:1161588342  说明加好友原因

  4. vue常用

    vue常用的路由的状态管理

  5. mysql case, if

    if语句: 用法和excel的if函数很像 if(expr1, value_if_expr1_is_true, value_if_expr1_is_false) select if(tag = 3, ...

  6. RISC处理器

     RISC(精简指令集算法)处理器是经过硬件的精简只执行很有限的最常用的那部分指令的处理器.因为通过研究发现,只有 大约 20%的指令是最常用的,把处理器能执行的指令数目减少到 最低限度,对它们的执行 ...

  7. 趣味编程:24点(Haskell版)

    24 game/Solve import Data.List import Data.Ratio import Control.Monad data Expr = Constant Rational ...

  8. 常用类一一MATH类一一两个静态常量PI 和E,一些数学函数。

    package test; public class MathTest { public static void main(String[] args) { System.out.println(Ma ...

  9. select 中添加option的注意

    在平时写JS中经常要给Select添加option,如果我们把option中的数据用一个字符串来表示: eg: var strOption='<option>1</option> ...

  10. 内核线程和用户线程(SMP)

    用户级和内核级线程 用户级线程:任何应用程序都可以通过使用线程库设计成多线程程序.线程库是用于用户级线程管理的一个例程句,它包含用于创建和销毁线程的代码.在线程间传递消息和数据的代码.调度线程执行的代 ...