使用HttpClient 发送 GET、POST(FormData、Raw)、PUT、Delete请求及文件上传
httpclient4.3.6
- package org.caeit.cloud.dev.util;
- import java.io.File;
- import java.io.IOException;
- import java.io.UnsupportedEncodingException;
- import java.nio.charset.Charset;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
- import java.util.Set;
- import org.apache.http.HttpEntity;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.CloseableHttpResponse;
- import org.apache.http.client.methods.HttpDelete;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.client.methods.HttpPut;
- 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.impl.client.CloseableHttpClient;
- import org.apache.http.impl.client.HttpClientBuilder;
- import org.apache.http.impl.client.HttpClients;
- import org.apache.http.message.BasicNameValuePair;
- import org.apache.http.util.EntityUtils;
- import org.caeit.cloud.dev.entity.HttpResponse; // no use
- public class HttpClientUtil {
- /**
- * 发送http get请求
- */
- public static HttpResponse httpGet(String url,Map<String,String> headers,String encode){
- HttpResponse response = new HttpResponse();
- if(encode == null){
- encode = "utf-8";
- }
- String content = null;
- //since 4.3 不再使用 DefaultHttpClient
- CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
- HttpGet httpGet = new HttpGet(url);
- //设置header
- if (headers != null && headers.size() > 0) {
- for (Map.Entry<String, String> entry : headers.entrySet()) {
- httpGet.setHeader(entry.getKey(),entry.getValue());
- }
- }
- CloseableHttpResponse httpResponse = null;
- try {
- httpResponse = closeableHttpClient.execute(httpGet);
- HttpEntity entity = httpResponse.getEntity();
- content = EntityUtils.toString(entity, encode);
- response.setBody(content);
- response.setHeaders(httpResponse.getAllHeaders());
- response.setReasonPhrase(httpResponse.getStatusLine().getReasonPhrase());
- response.setStatusCode(httpResponse.getStatusLine().getStatusCode());
- } catch (Exception e) {
- e.printStackTrace();
- }finally{
- try {
- httpResponse.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- try { //关闭连接、释放资源
- closeableHttpClient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return response;
- }
- /**
- * 发送 http post 请求,参数以form表单键值对的形式提交。
- */
- public static HttpResponse httpPostForm(String url,Map<String,String> params, Map<String,String> headers,String encode){
- HttpResponse response = new HttpResponse();
- if(encode == null){
- encode = "utf-8";
- }
- //HttpClients.createDefault()等价于 HttpClientBuilder.create().build();
- CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
- HttpPost httpost = new HttpPost(url);
- //设置header
- if (headers != null && headers.size() > 0) {
- for (Map.Entry<String, String> entry : headers.entrySet()) {
- httpost.setHeader(entry.getKey(),entry.getValue());
- }
- }
- //组织请求参数
- List<NameValuePair> paramList = new ArrayList <NameValuePair>();
- if(params != null && params.size() > 0){
- Set<String> keySet = params.keySet();
- for(String key : keySet) {
- paramList.add(new BasicNameValuePair(key, params.get(key)));
- }
- }
- try {
- httpost.setEntity(new UrlEncodedFormEntity(paramList, encode));
- } catch (UnsupportedEncodingException e1) {
- e1.printStackTrace();
- }
- String content = null;
- CloseableHttpResponse httpResponse = null;
- try {
- httpResponse = closeableHttpClient.execute(httpost);
- HttpEntity entity = httpResponse.getEntity();
- content = EntityUtils.toString(entity, encode);
- response.setBody(content);
- response.setHeaders(httpResponse.getAllHeaders());
- response.setReasonPhrase(httpResponse.getStatusLine().getReasonPhrase());
- response.setStatusCode(httpResponse.getStatusLine().getStatusCode());
- } catch (Exception e) {
- e.printStackTrace();
- }finally{
- try {
- httpResponse.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- try { //关闭连接、释放资源
- closeableHttpClient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return response;
- }
- /**
- * 发送 http post 请求,参数以原生字符串进行提交
- * @param url
- * @param encode
- * @return
- */
- public static HttpResponse httpPostRaw(String url,String stringJson,Map<String,String> headers, String encode){
- HttpResponse response = new HttpResponse();
- if(encode == null){
- encode = "utf-8";
- }
- //HttpClients.createDefault()等价于 HttpClientBuilder.create().build();
- CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
- HttpPost httpost = new HttpPost(url);
- //设置header
- httpost.setHeader("Content-type", "application/json");
- if (headers != null && headers.size() > 0) {
- for (Map.Entry<String, String> entry : headers.entrySet()) {
- httpost.setHeader(entry.getKey(),entry.getValue());
- }
- }
- //组织请求参数
- StringEntity stringEntity = new StringEntity(stringJson, encode);
- httpost.setEntity(stringEntity);
- String content = null;
- CloseableHttpResponse httpResponse = null;
- try {
- //响应信息
- httpResponse = closeableHttpClient.execute(httpost);
- HttpEntity entity = httpResponse.getEntity();
- content = EntityUtils.toString(entity, encode);
- response.setBody(content);
- response.setHeaders(httpResponse.getAllHeaders());
- response.setReasonPhrase(httpResponse.getStatusLine().getReasonPhrase());
- response.setStatusCode(httpResponse.getStatusLine().getStatusCode());
- } catch (Exception e) {
- e.printStackTrace();
- }finally{
- try {
- httpResponse.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- try { //关闭连接、释放资源
- closeableHttpClient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return response;
- }
- /**
- * 发送 http put 请求,参数以原生字符串进行提交
- * @param url
- * @param encode
- * @return
- */
- public static HttpResponse httpPutRaw(String url,String stringJson,Map<String,String> headers, String encode){
- HttpResponse response = new HttpResponse();
- if(encode == null){
- encode = "utf-8";
- }
- //HttpClients.createDefault()等价于 HttpClientBuilder.create().build();
- CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
- HttpPut httpput = new HttpPut(url);
- //设置header
- httpput.setHeader("Content-type", "application/json");
- if (headers != null && headers.size() > 0) {
- for (Map.Entry<String, String> entry : headers.entrySet()) {
- httpput.setHeader(entry.getKey(),entry.getValue());
- }
- }
- //组织请求参数
- StringEntity stringEntity = new StringEntity(stringJson, encode);
- httpput.setEntity(stringEntity);
- String content = null;
- CloseableHttpResponse httpResponse = null;
- try {
- //响应信息
- httpResponse = closeableHttpClient.execute(httpput);
- HttpEntity entity = httpResponse.getEntity();
- content = EntityUtils.toString(entity, encode);
- response.setBody(content);
- response.setHeaders(httpResponse.getAllHeaders());
- response.setReasonPhrase(httpResponse.getStatusLine().getReasonPhrase());
- response.setStatusCode(httpResponse.getStatusLine().getStatusCode());
- } catch (Exception e) {
- e.printStackTrace();
- }finally{
- try {
- httpResponse.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- try {
- closeableHttpClient.close(); //关闭连接、释放资源
- } catch (IOException e) {
- e.printStackTrace();
- }
- return response;
- }
- /**
- * 发送http delete请求
- */
- public static HttpResponse httpDelete(String url,Map<String,String> headers,String encode){
- HttpResponse response = new HttpResponse();
- if(encode == null){
- encode = "utf-8";
- }
- String content = null;
- //since 4.3 不再使用 DefaultHttpClient
- CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
- HttpDelete httpdelete = new HttpDelete(url);
- //设置header
- if (headers != null && headers.size() > 0) {
- for (Map.Entry<String, String> entry : headers.entrySet()) {
- httpdelete.setHeader(entry.getKey(),entry.getValue());
- }
- }
- CloseableHttpResponse httpResponse = null;
- try {
- httpResponse = closeableHttpClient.execute(httpdelete);
- HttpEntity entity = httpResponse.getEntity();
- content = EntityUtils.toString(entity, encode);
- response.setBody(content);
- response.setHeaders(httpResponse.getAllHeaders());
- response.setReasonPhrase(httpResponse.getStatusLine().getReasonPhrase());
- response.setStatusCode(httpResponse.getStatusLine().getStatusCode());
- } catch (Exception e) {
- e.printStackTrace();
- }finally{
- try {
- httpResponse.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- try { //关闭连接、释放资源
- closeableHttpClient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return response;
- }
- /**
- * 发送 http post 请求,支持文件上传
- */
- public static HttpResponse httpPostFormMultipart(String url,Map<String,String> params, List<File> files,Map<String,String> headers,String encode){
- HttpResponse response = new HttpResponse();
- if(encode == null){
- encode = "utf-8";
- }
- CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
- HttpPost httpost = new HttpPost(url);
- //设置header
- if (headers != null && headers.size() > 0) {
- for (Map.Entry<String, String> entry : headers.entrySet()) {
- httpost.setHeader(entry.getKey(),entry.getValue());
- }
- }
- MultipartEntityBuilder mEntityBuilder = MultipartEntityBuilder.create();
- mEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
- mEntityBuilder.setCharset(Charset.forName(encode));
- // 普通参数
- ContentType contentType = ContentType.create("text/plain",Charset.forName(encode));//解决中文乱码
- if (params != null && params.size() > 0) {
- Set<String> keySet = params.keySet();
- for (String key : keySet) {
- mEntityBuilder.addTextBody(key, params.get(key),contentType);
- }
- }
- //二进制参数
- if (files != null && files.size() > 0) {
- for (File file : files) {
- mEntityBuilder.addBinaryBody("file", file);
- }
- }
- httpost.setEntity(mEntityBuilder.build());
- String content = null;
- CloseableHttpResponse httpResponse = null;
- try {
- httpResponse = closeableHttpClient.execute(httpost);
- HttpEntity entity = httpResponse.getEntity();
- content = EntityUtils.toString(entity, encode);
- response.setBody(content);
- response.setHeaders(httpResponse.getAllHeaders());
- response.setReasonPhrase(httpResponse.getStatusLine().getReasonPhrase());
- response.setStatusCode(httpResponse.getStatusLine().getStatusCode());
- } catch (Exception e) {
- e.printStackTrace();
- }finally{
- try {
- httpResponse.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- try { //关闭连接、释放资源
- closeableHttpClient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return response;
- }
- }
发送Get请求:
HttpResponse httpGet(String url,Map<String,String> headers,String encode)
发送Post请求,同表单Post提交
HttpResponse httpPostForm(String url,Map<String,String> params, Map<String,String> headers,String encode)
发送Post Raw请求
HttpResponse httpPostRaw(String url,String stringJson,Map<String,String> headers, String encode)
发送Put Raw请求
HttpResponse httpPutRaw(String url,String stringJson,Map<String,String> headers, String encode)
发送Delete请求
HttpResponse httpDelete(String url,Map<String,String> headers,String encode)
说明:
1、since 4.3 不再使用 DefaultHttpClient
2、UrlEncodedFormEntity 与 StringEntity 区别
2.1、UrlEncodedFormEntity()的形式比较单一,只能是普通的键值对,局限性相对较大。
2.2、而StringEntity()的形式比较自由,只要是字符串放进去,不论格式都可以。
3、以raw方式发送请求时,需指定 Content type:httpost.setHeader("Content-type", "application/json"); 否则默认使用 Content type 'text/plain;charset=UTF-8'。
原文地址:http://huangqiqing123.iteye.com/blog/2344680
使用HttpClient 发送 GET、POST(FormData、Raw)、PUT、Delete请求及文件上传的更多相关文章
- 使用HttpClient 发送 GET、POST、PUT、Delete请求及文件上传
package org.caeit.cloud.dev.util; import java.io.File; import java.io.IOException; import java.io.Un ...
- 【H5】-- FormData用法介绍以及实现图片/文件上传--【XUEBIG】
一.概述 FormData 对象的使用: 1.用一些键值对来模拟一系列表单控件:即把form中所有表单元素的name与value组装成一个queryString 2. 异步上传二进制文件. 二.使 ...
- SpringCloud 之 Fegin —— 发送GET、POST请求以及文件上传
由于项目需要调用其他微服务的数据,首先想到的就是写一个http网络请求的工具类,但是想到在之前看springCloud的时候里面有这个Fegin可以实现,就顺便实践一下,虽然过程有点坎坷,好在都顺利解 ...
- multipart/form-data请求与文件上传
要上传文件,需要用post方法,并且设置enctype为multipart/form-data. <form action="/upload" method="po ...
- multipart/form-data请求与文件上传的细节
<!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8" ...
- python 全栈开发,Day75(Django与Ajax,文件上传,ajax发送json数据,基于Ajax的文件上传,SweetAlert插件)
昨日内容回顾 基于对象的跨表查询 正向查询:关联属性在A表中,所以A对象找关联B表数据,正向查询 反向查询:关联属性在A表中,所以B对象找A对象,反向查询 一对多: 按字段:xx book ----- ...
- Django与Ajax,文件上传,ajax发送json数据,基于Ajax的文件上传,SweetAlert插件
一.Django与Ajax AJAX准备知识:JSON 什么是 JSON ? JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation) JSON 是轻 ...
- Multipart/form-data POST文件上传详解
Multipart/form-data POST文件上传详解 理论 简单的HTTP POST 大家通过HTTP向服务器发送POST请求提交数据,都是通过form表单提交的,代码如下: <form ...
- Multipart/form-data POST文件上传详解(转)
Multipart/form-data POST文件上传详解 理论 简单的HTTP POST 大家通过HTTP向服务器发送POST请求提交数据,都是通过form表单提交的,代码如下: <form ...
随机推荐
- bzoj3622已经没有什么好害怕的了
bzoj3622已经没有什么好害怕的了 题意: 给n个数Ai,n个数Bi,将Ai中的数与Bi中的数配对,求配对Ai比Bi大的比Bi比Ai大的恰好有k组的方案数.n,k≤2000 题解: 蒟蒻太弱了只能 ...
- 证明:ThreadLocal的get,set方法无法防止内存泄漏
先给出结论:get,set两个方法都不能完全防止内存泄漏,还是每次用完ThreadLocal都勤奋的remove一下靠谱. 前言: 看到有的博客说在把ThreadLocal的所有强引用置空前,调用 ...
- ant-design-vue中实现modal模态框的复用(添加,编辑展示同一个模态框)
用两个button(添加,编辑)按钮展示同一个模态框,并不是什么大问题,问题在于解决这两个模态框得有自己的确定和取消方法 父页面完全接管子页面(利于子页面复用) 父页面代码: <template ...
- 软件测试工程师入门——Linux【使用说明书】
先来说一下linux是什么? linux 是一个开源.免费的操作系统,其稳定性.安全性.处理多并发已经得到业界的认可,目前很多中性,大型甚至是巨型项目都在使用linux. linux 内核:redha ...
- try-catch- finally块中, finally块唯一不执行的情况是什么?
除非在try块或者catch块中调用了退出虚拟机的方法(即System.exit(1);),否则不管在try块.catch块中执行怎样的代码,出现怎样的情况,异常处理的finally块总是会被执行的 ...
- Java顺序查找、二分查找
Java顺序查找.二分查找 查找算法中顺序查找算是最简单的了,无论是有序的还是无序的都可以,只需要一个个对比即可,但其实效率很低. 顺序查找 动图演示 详细代码 // 顺序查找 public st ...
- Zabbix4.x如何安全传输数据
由于设备都在混合云,所以不少数据传输是通过公网,这样极大的增加了危险性,所以在Zabbix数据传输这块则进行PSK安全认证,由proxy主动收集agent数据后统一发送给server,这样只需要对pr ...
- wpf文字模糊
wpf如果使用了DropShadowEffect,会导致文字模糊,可以在window上设置 this.UseLayoutRounding = true;解决此问题
- Spring bean初始化
- web自动化 -- HTMLreport(三)测试报告输出log日志
一.需求痛点 1.HTMLreport没法看到log日志,经过封装的框架不可能走一步就print() 2. 希望可以在HTMLreport中输出log日志 3.痛点截图 二.解决办法 1.既然是HTM ...