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请求及文件上传的更多相关文章

  1. 使用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 ...

  2. Django 10 GET和POST(HttpRequest对象,GET和POST请求,文件上传,HttpResponse对象的cookie)

    Django 10 GET和POST(HttpRequest对象,GET和POST请求,文件上传,HttpResponse对象的cookie) 一.HttpRequest对象 #HttpRequest ...

  3. Android okHttp网络请求之文件上传下载

    前言: 前面介绍了基于okHttp的get.post基本使用(http://www.cnblogs.com/whoislcj/p/5526431.html),今天来实现一下基于okHttp的文件上传. ...

  4. SpringCloud 之 Fegin —— 发送GET、POST请求以及文件上传

    由于项目需要调用其他微服务的数据,首先想到的就是写一个http网络请求的工具类,但是想到在之前看springCloud的时候里面有这个Fegin可以实现,就顺便实践一下,虽然过程有点坎坷,好在都顺利解 ...

  5. 测试平台系列(92) 让http请求支持文件上传

    大家好~我是米洛! 我正在从0到1打造一个开源的接口测试平台, 也在编写一套与之对应的教程,希望大家多多支持. 欢迎关注我的公众号米洛的测开日记,获取最新文章教程! 回顾 上一节呢,我们编写了oss的 ...

  6. Laravel请求/Cookies/文件上传

    一.HTTP请求 1.基本示例:通过依赖注入获取当前 HTTP 请求实例,应该在控制器的构造函数或方法中对Illuminate\Http\Request 类进行类型提示,当前请求实例会被服务容器自动注 ...

  7. Android 普通okhttp、okhttp utils执行 post get请求,文件上传下载、请求图片

    public class OKHttpActivity extends Activity implements View.OnClickListener { public static final M ...

  8. 前端笔记之微信小程序(三)GET请求案例&文件上传和相册API&配置https

    一.信息流小程序-GET请求案例 1.1服务端接口开发 一定要养成接口的意识,前端单打独斗出不来任何效果,必须有接口配合,写一个带有分页.关键词查询的接口: 分页接口:http://127.0.0.1 ...

  9. springboot 文件上传及java使用post请求模拟文件上传

    参考自:https://blog.csdn.net/qq_25958999/article/details/83988974 接收端Controller类中方法: @RequestMapping(va ...

随机推荐

  1. Fine报表权限流程分析记录

    Fine报表权限流程分析记录 URL访问三种类型的报表:第一个:BI报表 例如: http://192.25.103.250:37799/WebReport/ReportServer?op=fr_bi ...

  2. C++设计模式 之 “对象性能” 模式:Singleton、Flyweight

    “对象性能”模式 面向对象很好地解决了“抽象”的问题,但是必不可免地要付出一定的代价.对于通常情况来讲,面向对象的成本大都可以忽略不计.但是某些情况,面向对象所带来的成本必须谨慎处理. 典型模式 # ...

  3. 20135234mqy-——信息安全系统设计基础第十一周学习总结

    第八章 异常控制流 8.1异常 异常是异常控制流的一种形式,它一部分是由硬件实现的,一部分是由操作系统实现的. 异常就是控制流中的突变,用来响应处理器状态中的某些变化. 8.1.1异常处理 异常号是到 ...

  4. 20165211 学习基础和C语言调查

    20165211 学习基础和C语言调查 理论脱离实践是最大的不幸.--达芬奇 达芬奇,是我眼里最有嫌疑的穿越者. 绘画.天文.雕塑.音乐.发明.建筑,数学.生理.物理.天文.地质--我很难想象有一个人 ...

  5. Python3基础 else 循环完整结束才执行

             Python : 3.7.0          OS : Ubuntu 18.04.1 LTS         IDE : PyCharm 2018.2.4       Conda ...

  6. linux磁盘分区详解【转】

    本文装载自:http://blog.csdn.net/aaronychen/article/details/2270048#comments 在学习 Linux 的过程中,安装 Linux 是每一个初 ...

  7. AcceptAsync和BeginAccept的区别

    Difference between […]Async and Begin[…] .net asynchronous APIs Note that most *Async methods (with ...

  8. 【查看内存参数详解】Linux free -m 详细说明

    free 命令相对于top 提供了更简洁的查看系统内存使用情况:$ free                                       total            used   ...

  9. [luogu 1070]道路游戏(NOIP2009T4)

    题目链接 题解: 题目描述好长啊.... 大概就是设一下$f[i]$表示第i秒的最大价值 首先枚举时间,然后因为机器人这一秒无论在哪里都是有可能的,所以要枚举一下每个点,又因为最多走p秒所以再枚举一下 ...

  10. [不屈的复习] - http://how2j.cn/

    http://how2j.cn/ 该教程网站分得比较规整!