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. noip2015 day1

    不解释,很简单,直接按照题目的方法构造就行了 Code #include<iostream> #include<cstdio> #include<cctype> # ...

  2. [noip模拟题]排队

    [问题描述] 小sin所在的班有n名同学,正准备排成一列纵队,但他们不想按身高从矮到高排,那样太单调,太没个性.他们希望恰好有k对同学是高的在前,矮的在后,其余都是矮的在前,高的在后.如当n=5,k= ...

  3. JavaScript:正则表达式 分组2

    继续上一篇的写,这篇复杂点. 分组+范围 var reg=/([abcd]bc)/g; var str="abcd bbcd cbcd dbcd"; console.log(str ...

  4. hdu 6444 网络赛 Neko's loop(单调队列 + 裴蜀定理)题解

    题意:有编号为0~n-1的n个游戏,每个活动都有一个价值(可为负),给你m,s和k,你可以从任意一个编号开始玩,但是下一个游戏必须是编号为(i + k)%n的游戏,你最多能玩m次游戏,问你如果最后你手 ...

  5. HDU1560 DNA sequence(IDA*)题解

    DNA sequence Time Limit: 15000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) To ...

  6. RedHat6使用CentOS yum源 换yum

    yum 简单介绍一下 yum 主要功能是更方便的添加/删除/更新RPM 包,自动解决包的倚赖性问题,便于管理大量系统的更新问题. yum 可以同时配置多个资源库(Repository),简洁的配置文件 ...

  7. Spring编译AOP项目报错

    警告: Exception encountered during context initialization - cancelling refresh attempt: org.springfram ...

  8. POJ 1222 EXTENDED LIGHTS OUT(高斯消元解XOR方程组)

    http://poj.org/problem?id=1222 题意:现在有5*6的开关,1表示亮,0表示灭,按下一个开关后,它上下左右的灯泡会改变亮灭状态,要怎么按使得灯泡全部处于灭状态,输出方案,1 ...

  9. python 编程基础练习 第一天

    python 编程基础练习 第一天: 需求: 1.计算2的38次方,180*0.7输出(精度显示正常), x的y次方,数字倒序输出即345876输出678543,方法越多越好. 2.字符串处理: 1) ...

  10. python 中的object与type的关系

    object 和 type的关系很像鸡和蛋的关系,先有object还是先有type没法说,obejct和type是共生的关系,必须同时出现的. 在看下去之前,也要请先明白,在Python里面,所有的东 ...