HttpClient4.6的使用
禁止转载,如需转载请联系本人
1)简介:
HttpClient是apache的开源项目,弥补了Java自带的URLConnection功能不足,操作繁琐的缺点。
2)简单使用:
a)get方式请求
/**
* 发送get请求,get表单提交
* 获取数返回的json数据
*/
@Test
public void httpGet() { //创建httpClient对象
HttpClient httpClient = HttpClients.createDefault();//4.3之后的都采用该方法生成httpClient对象
//创建url
String url = "http://localhost:8080/day29_struts/dataconvert?user.name=yyq&user.age=20&user.birthday=2012-8-9";
//创建httpGet对象
HttpGet httpget = new HttpGet(url);
System.out.println("URI:" + httpget.getURI());
System.out.println("requestLine:" + httpget.getRequestLine()); try { //执行get请求
HttpResponse response = httpClient.execute(httpget); //打印响应状态
System.out.println("响应状态:" + response.getStatusLine()); //获取响应体
HttpEntity entity = response.getEntity();
if (entity != null) {
//打印响应内容长度
System.out.println("内容长度:" + entity.getContentLength());
//打印响应类型
System.out.println("返回类型:" + entity.getContentType());
//响应体内容
System.out.println("实体内容:" + EntityUtils.toString(entity)); } } catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} } 结果:
URI:http://localhost:8080/day29_struts/dataconvert?user.name=yyq&user.age=20&user.birthday=2012-8-9
requestLine:GET http://localhost:8080/day29_struts/dataconvert?user.name=yyq&user.age=20&user.birthday=2012-8-9 HTTP/1.1
响应状态:HTTP/1.1 200 OK
内容长度:78
返回类型:Content-Type: text/html;charset=UTF-8
实体内容:{"user.name":yyq, "user.age":20, "user.birthday":Thu Aug 09 00:00:00 CST 2012}
b)post方式提交(表单提交推荐使用,编码好处理,而且请求数据没有限制)
/**
* 推荐方式
* 发送post请求,即表单post提交
*/
@Test
public void httpPost() {
//创建HttpClient实例
HttpClient httpClient = HttpClients.createDefault();
//URL
String url = "http://localhost:8080/test/TestServlet";
//获取HttpPost实例
HttpPost httpPost = new HttpPost(url);
System.out.println(httpPost.getRequestLine()); try {
//设置post请求参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", "10"));
params.add(new BasicNameValuePair("name", "yyq"));
//把参数装进post请求体
httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //获取response实例
HttpResponse response = httpClient.execute(httpPost); //响应状态
System.out.println(response.getStatusLine()); //获取响应体
HttpEntity entity = response.getEntity(); if (entity != null) { System.out.println(EntityUtils.toString(entity, "utf-8")); } } catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} } 结果:
POST http://localhost:8080/test/TestServlet HTTP/1.1
HTTP/1.1 200 OK
c)文件上传与下载
服务器端(采用tomcat)
package servlet; import java.io.File;
import java.io.IOException;
import java.util.List; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload; public class UploadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8"); //检测是不是存在上传文件,如果不存在则按一般方式解决
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) { try {
DiskFileItemFactory factory = new DiskFileItemFactory();
//指定在内存中缓存数据大小,单位为byte,这里设为1Mb
factory.setSizeThreshold(1024*1024);
//设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录 ,老提示找不到路径,气得要死,无奈注释掉用tomcat自带的temp目录
//factory.setRepository(new File(getServletContext().getRealPath("uploadFile/tem"))); //实例化文件上传对象
ServletFileUpload upload = new ServletFileUpload(factory);
//设置单个文件最大限制
upload.setFileSizeMax(500*1024*1024);
//设置总文件限制
upload.setSizeMax(200*1024*1024);
//设置编码
upload.setHeaderEncoding("utf-8");
//设置监视器,显示上传进度 //解析请求
List<FileItem> items = upload.parseRequest(request);
//解析表单
if (items != null) {
System.out.println(items.size()); for (FileItem fileItem : items) { //如果是普通表单格式
if (fileItem.isFormField()) { response.getWriter().print("---普通文本内容---");
System.out.println("文本类型:" + fileItem.getContentType());
System.out.println("表单属性名:" + fileItem.getFieldName());
System.out.println("表单值:" + fileItem.getString("utf-8")); } else { System.out.println("表单属性名:" + fileItem.getFieldName());
//上传的文件名
String fileName = fileItem.getName();
//把文件写在当前应用的upload目录
String basePath = getServletContext().getRealPath("/upload");
fileItem.write(new File(basePath, fileName));
//删除缓存区
fileItem.delete(); } } } } catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} } else { } } @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
} }
客户端:
/**
* 上传文件,post方式
* 包含普通内容和上传的文件
*/
@Test
public void fileUpload() { HttpClient httpClient = HttpClients.createDefault(); String url = "http://localhost:8080/test/UploadServlet";
HttpPost httpPost = new HttpPost(url); /**
* 封装到HttpEneity中
* 使用MultipartEntityBuilder.create().build()生成该对象
* 原来的new MultipartEntity()已废弃
*
* 封装请求体的两种方式:
* 1,可以创建StringBody和FileBody封装文本和文件
* 2,直接使用MultipartEntityBuilder.create()
* 的addBinaryBody(name, File)封装文件
* addTextBody(name, text, ContentType)封装文本
*/
//普通数据的封装
StringBody sb = new StringBody("yyq",
ContentType.create("text/plain", "utf-8")); //文件封装
FileBody fb = new FileBody(new File("E:/App/CodeBlocks.zip"));
HttpEntity reqEntity = MultipartEntityBuilder.create()
// .addPart("name", sb)
.addTextBody("name", "yyq2", ContentType.create("text/plain", "utf-8"))
// .addPart("file", fb)
.addBinaryBody("name", new File("E:/App/CodeBlocks.zip"))
.build(); //4,请求体封装到post中
httpPost.setEntity(reqEntity); try {
HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); if (response.getStatusLine().getStatusCode() == 200) {
System.out.println(EntityUtils.toString(entity, "utf-8"));
} } catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} }
附:HTTPUtils,同步方式,异步还是okhttp吧
public class HttpClientUtil { public static String doGet(String url, Map<String, String> param) { // 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault(); String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build(); // 创建http GET请求
HttpGet httpGet = new HttpGet(uri); // 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
} public static String doGet(String url) {
return doGet(url, null);
} public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} return resultString;
} public static String doPost(String url) {
return doPost(url, null);
} public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} return resultString;
}
}
HttpClient4.6的使用的更多相关文章
- Atitit 类库冲突解决方案 httpclient-4.5.2.jar
Atitit 类库冲突解决方案 httpclient-4.5.2.jar 错误提示如下1 版本如下(client and selenium)2 解决流程2 挂载源码 (SSLConnectionSo ...
- httpclient4.3.6/httpcore-4.4自己封装的工具类
引入jar包 httpclient4.3.6/httpcore-4.4 package com.develop.util; import java.io.IOException; import jav ...
- httpclient4.3 工具类
httpclient4.3 java工具类. .. .因项目须要开发了一个工具类.正经常常使用的httpclient 请求操作应该都够用了 工具类下载地址:http://download.csdn. ...
- HttpClient4.0
****************************HttpClient4.0用法***************************** 1.初始化HttpParams,设置组件参数 //Ht ...
- [置顶] android网络通讯之HttpClient4不指定参数名发送Post
在HttpClient4之前都是通过List<NameValuePair>键值对的形式来向服务器传递参数 ,在4.0版本中在加入了不指定参数名发送数据的形式,利用StringEntity来 ...
- HttpClient4的使用,模拟浏览器登陆新浪微博,发表微博和文字+图片微博
HttpClient4,最原始的需求就是使用其来模拟浏览器想服务器发起http请求,当然,他的功能不止于此,但是我需要的就是这个功能而已,jdk也有其自带的类似的api:UrlConnection,效 ...
- HttpClient4.5 post请求xml到服务器
1.加入HttpClient4.5和junit依赖包 <dependencies> <dependency> <groupId>org.apache.httpcom ...
- Java模拟http上传文件请求(HttpURLConnection,HttpClient4.4,RestTemplate)
先上代码: public void uploadToUrl(String fileId, String fileSetId, String formUrl) throws Throwable { St ...
- 使用HttpClient4.5实现HTTPS的双向认证
说明:本文主要是在平时接口对接开发中遇到的为保证传输安全的情况特要求使用https进行交互的情况下,使用httpClient4.5版本对HTTPS的双向验证的 功能的实现 首先,老生常谈,文章 ...
- HttpClient4.5.2调用示例(转载+原创)
操作HttpClient时的一个工具类,使用是HttpClient4.5.2 package com.xxxx.charactercheck.utils; import java.io.File; i ...
随机推荐
- translate 实现元素垂直居中
<div class="demo2"> <span>about me</span> </div> css .demo2{ width ...
- SpringMvc之参数绑定注解详解之一
引言: 前段时间项目中用到了REST风格来开发程序,但是当用POST.PUT模式提交数据时,发现服务器端接受不到提交的数据(服务器端参数绑定没有加 任何注解),查看了提交方式为application/ ...
- Linux部署walle
背景:Walle 一个web部署系统工具,配置简单.功能完善.界面流畅.开箱即用!支持git.svn版本管理,支持各种web代码发布,PHP,Python,JAVA等代码的发布.回滚,可以通过web来 ...
- #410(div2)B. Mike and strings
time limit per test 2 seconds memory limit per test 256 megabytes input standard input output standa ...
- 【总结整理】JQuery基础学习---样式篇
进入官方网站获取最新的版本 http://jquery.com/download/ 中文 https://www.jquery123.com/ <!--JQuery:轻量级的JavaScr ...
- 文件格式——gff格式
Gff文件格式 gff格式是Sanger研究所定义,是一种简单的.方便的对于DNA.RNA以及蛋白质序列的特征进行描述的一种数据格式,已经成为序列注释的通用格式,比如基因组的基因预测,许多软件都支持输 ...
- 【C#】清除webBrowser 缓存和Cookie的解决方案
试了很多方法,最后发现万剑大哥的方法管用,转载一下 转自:https://www.cnblogs.com/midcn/p/3527123.html 通过测试webBrowser与IE缓存和Cookie ...
- linux添加软件的service start/stop快捷服务(简单版)
首先我们先需要一款软件,例如“apache” 安装解压至相应目录“/home/aaa/apache” 开始操作:进入“/etc/init.d/”中,新建一个service服务运行脚本“tomcat”, ...
- 为什么要使用func.call(this)
1.为什么要使用func.call(this) 在正常模式下,js 函数里那些你没有声明就使用的变量,其实是访问的全局对象的属性.但是在严格模式下,不允许这种语法,所有变量都必须要显示声明,所以如果你 ...
- matplotlib.pyplot import报错: ValueError: _getfullpathname: embedded null character in path
Environment: Windows 10, Anaconda 3.6 matplotlib 2.0 import matplotlib.pyplot 报错: ValueError: _getfu ...