使用HttpClient 发送 GET、POST、PUT、Delete请求及文件上传
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; 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、PUT、Delete请求及文件上传的更多相关文章
- 使用HttpClient 发送 GET、POST(FormData、Raw)、PUT、Delete请求及文件上传
httpclient4.3.6 package org.caeit.cloud.dev.util; import java.io.File; import java.io.IOException; i ...
- Django 10 GET和POST(HttpRequest对象,GET和POST请求,文件上传,HttpResponse对象的cookie)
Django 10 GET和POST(HttpRequest对象,GET和POST请求,文件上传,HttpResponse对象的cookie) 一.HttpRequest对象 #HttpRequest ...
- Android okHttp网络请求之文件上传下载
前言: 前面介绍了基于okHttp的get.post基本使用(http://www.cnblogs.com/whoislcj/p/5526431.html),今天来实现一下基于okHttp的文件上传. ...
- SpringCloud 之 Fegin —— 发送GET、POST请求以及文件上传
由于项目需要调用其他微服务的数据,首先想到的就是写一个http网络请求的工具类,但是想到在之前看springCloud的时候里面有这个Fegin可以实现,就顺便实践一下,虽然过程有点坎坷,好在都顺利解 ...
- 测试平台系列(92) 让http请求支持文件上传
大家好~我是米洛! 我正在从0到1打造一个开源的接口测试平台, 也在编写一套与之对应的教程,希望大家多多支持. 欢迎关注我的公众号米洛的测开日记,获取最新文章教程! 回顾 上一节呢,我们编写了oss的 ...
- Laravel请求/Cookies/文件上传
一.HTTP请求 1.基本示例:通过依赖注入获取当前 HTTP 请求实例,应该在控制器的构造函数或方法中对Illuminate\Http\Request 类进行类型提示,当前请求实例会被服务容器自动注 ...
- Android 普通okhttp、okhttp utils执行 post get请求,文件上传下载、请求图片
public class OKHttpActivity extends Activity implements View.OnClickListener { public static final M ...
- 前端笔记之微信小程序(三)GET请求案例&文件上传和相册API&配置https
一.信息流小程序-GET请求案例 1.1服务端接口开发 一定要养成接口的意识,前端单打独斗出不来任何效果,必须有接口配合,写一个带有分页.关键词查询的接口: 分页接口:http://127.0.0.1 ...
- springboot 文件上传及java使用post请求模拟文件上传
参考自:https://blog.csdn.net/qq_25958999/article/details/83988974 接收端Controller类中方法: @RequestMapping(va ...
随机推荐
- Google's Machine Learning Crash Course #03# Reducing Loss
Goal of training a model is to find a set of weights and biases that have low loss, on average, acro ...
- 根据wsdl文件,Java工程自动生成webservice客户端调用
根据wsdl文件,Java工程自动生成webservice客户端调用 1,工具:带有webservice插件的myeclips 2,步骤: (1),新建一个Java工程:relationship (2 ...
- 04: Dom
目录: 参考W3school 1.1 获取标签:直接选择器和间接选择器 1.2 操作标签 1.3 DOM其他操作 1.4 DOM绑定事件的三种方法 1.5 DOM可以绑定的事件 1.1 获取标签:直接 ...
- 20145333茹翔 Exp5 Adobe阅读器漏洞攻击
20145333茹翔 Exp5 Adobe阅读器漏洞攻击 实验过程 主机为kali的ip地址为:192.168.1.111.靶机windows xp 的ip地址为:192.168.1.110 使用命令 ...
- 20145319 《网络渗透》URL攻击
20145319 <网络渗透>URL攻击 实验步骤 首先启动apache2,打开我们的钓鱼网页,键入命令/etc/init.d/apache2 start 在浏览器中尝试着访问自己的ip地 ...
- 我们能从 jQuery 的一个正则表达式中学到什么?
注意,该篇文章当前为粗糙的 v0.9 版本,会在稍后润色更新. 让我们来看一道思考题,根据 rejectExp,分析其正则执行过程中如何进行过滤?包含哪些执行步骤? rejectExp 变量的值如下: ...
- JavaScript 各种验证收集
filter或者forEach函数,可能是因为你的浏览器还不够新,暂时不支持新标准的函数,你可以使用如下方式自己定义: if (!Array.prototype.forEach) { Array.pr ...
- excel依赖的dll
依赖的先后顺序 stdole.dll office.dll Microsoft.Vbe.Interop.dll Microsoft.Office.Interop.Excel.dll Interop是i ...
- 51nod 1137 矩阵乘法
基本的矩阵乘法 中间for(int j=0;i<n;i++) //这里写错了 应该是j<n 晚上果然 效率不行 等会早点儿睡 //矩阵乘法 就是 两个矩阵 第一个矩阵的列 等与 第 ...
- SublimeText3常用快捷键和优秀插件(亲测)
SublimeText3常用快捷键和优秀插件 SublimeText是前端的一个神器,以其精简和可DIY而让广大fans疯狂.好吧不吹了直入正题 -_-!! 首先是安装,如果你有什么软件管家的话搜一下 ...