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

  1. 使用HttpClient 发送 GET、POST、PUT、Delete请求及文件上传

    package org.caeit.cloud.dev.util; import java.io.File; import java.io.IOException; import java.io.Un ...

  2. 【H5】-- FormData用法介绍以及实现图片/文件上传--【XUEBIG】

      一.概述 FormData 对象的使用: 1.用一些键值对来模拟一系列表单控件:即把form中所有表单元素的name与value组装成一个queryString 2. 异步上传二进制文件. 二.使 ...

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

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

  4. multipart/form-data请求与文件上传

    要上传文件,需要用post方法,并且设置enctype为multipart/form-data. <form action="/upload" method="po ...

  5. multipart/form-data请求与文件上传的细节

    <!DOCTYPE html><html><head lang="en">  <meta charset="UTF-8" ...

  6. python 全栈开发,Day75(Django与Ajax,文件上传,ajax发送json数据,基于Ajax的文件上传,SweetAlert插件)

    昨日内容回顾 基于对象的跨表查询 正向查询:关联属性在A表中,所以A对象找关联B表数据,正向查询 反向查询:关联属性在A表中,所以B对象找A对象,反向查询 一对多: 按字段:xx book ----- ...

  7. Django与Ajax,文件上传,ajax发送json数据,基于Ajax的文件上传,SweetAlert插件

    一.Django与Ajax AJAX准备知识:JSON 什么是 JSON ? JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation) JSON 是轻 ...

  8. Multipart/form-data POST文件上传详解

    Multipart/form-data POST文件上传详解 理论 简单的HTTP POST 大家通过HTTP向服务器发送POST请求提交数据,都是通过form表单提交的,代码如下: <form ...

  9. Multipart/form-data POST文件上传详解(转)

    Multipart/form-data POST文件上传详解 理论 简单的HTTP POST 大家通过HTTP向服务器发送POST请求提交数据,都是通过form表单提交的,代码如下: <form ...

随机推荐

  1. 02 drf源码剖析之快速了解drf

    02 drf源码剖析之快速了解drf 目录 02 drf源码剖析之快速了解drf 1. 什么是drf 2. 安装 3. 使用 3. DRF的应用场景 1. 什么是drf drf是一个基于django开 ...

  2. SQLAlchemy(四):SQLAlchemy查询高级

    目录 SQLAlchemy04 /SQLAlchemy查询高级 1.排序 2.limit.offset和切片操作 3.懒加载 4.group_by 5.having 6.join 7.subquery ...

  3. 一篇文章,学会jmeter模拟文件上传、下载操作

    最近很多同学都在问jmeter上传,下载文件的脚本怎么做? 正巧这阵子忙完有时间,就来“折腾”一番,哈哈 现整理出来和大家分享 到底该怎么做? 一.准备工作: 上传接口一个(自行开发解决了) 下载接口 ...

  4. This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary lo的解决办法

    创建存储过程时,出错信息: ERROR 1418 (HY000): This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA ...

  5. 哈夫曼编码+python实现

    关于哈夫曼树怎么构建的.哈夫曼编码怎么求,请参考 哈夫曼树及python实现 这些基础的东西就不在这里阐述了,本文直接上代码. 参考链接:哈夫曼树的 Python 实现 哈夫曼树的构建和编码 ''' ...

  6. [redis] -- 为什么那么快

    1 完全基于内存 2 数据结构简单,对数据操作也简单 3 只有单线程,避免了不必要的上下文切换,也不存在竞态,不存在多进程或多线程导致的切换而消耗CPU,不用开了各种锁的问题 4 使用多路IO复用模型 ...

  7. python---filecmp 实现文件,目录,遍历子目录的差异对比功能。

    python---filecmp ilecmp可以实现文件,目录,遍历子目录的差异对比功能. 自带filecmp模块,无需安装. 常用方法说明 filecmp提供3个操作方法,cmp(单文件对比),c ...

  8. NFS /etc/exports参数解释

    nfs 安装 执行以下命令安装 nfs 服务器所需的软件包 yum install -y nfs-utils 执行命令 vim /etc/exports,创建 exports 文件,文件内容如下: / ...

  9. 图解Kubernetes——故障排查指南

    针对越来多的Kubernetes容器云,对Kubernetes集群的故障排查却成了一个棘手问题.本文虫虫给大家以直观图示方式介绍如何排查Kubernetes的故障.该篇是系列文章续——故障排查篇. 概 ...

  10. jmeter之断言复制过来的内容也会失败

    今天遇到个很纳闷的事儿,就决定记下来,在做jmeter断言的时候,明明我是从相应文本中拷贝出来的内容,但是依旧会断言失败,差了很多资料无果,最终请教了大佬才发现是特殊字符的问题 jmeter断言中不会 ...