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 ...
随机推荐
- Java中是构造器创建对象吗?
首先,这里说明” Java中是构造器创建对象 “这句话是完全错误的. Java中构造器的作用主要是为了初始化变量的值...其实在执行构造器之前,Java对象所需要的内存空间,已经产生了... 一般可以 ...
- Makefile经典教程
转自:http://blog.csdn.net/ruglcc/article/details/7814546/ makefile很重要 什么是makefile?或许很多Winodws的程序 ...
- SQL连接、嵌套和集合查询---
SQL连接.嵌套和集合查询 一:连接查询 1 .不同表之间的连接查询 例 查询每个学生及其选修课程的情况. 本查询实际上是涉及Students与Reports两个表的连接操作.这两个表之间的联系是通过 ...
- JavaScript跳转和打开新窗口
跳转: window.location.href = "www.baidu.com" // 跳转到百度首页,不打开新的浏览器窗口 等价于html中的<a href=&quo ...
- [dp]编辑距离问题
https://www.51nod.com/tutorial/course.html#!courseId=3 转移方程: 注意如何对齐的. 这个算法的特点是,S和T字符串左边始终是对齐的.为了更好地理 ...
- 4. DVWA亲测暴力破解
LOW等级 我们先用burpsuite抓包,因为burpsuite提供了暴力破解模块 我们先创建一个1.txt文件夹,把正确的账号密码写进去 我们输入 Username:1 Password: ...
- es6基础系列五--数组的拓展
Array.from() 用于将两类对象转为真正的数组,类似数组对象和可遍历对象(包括数据结构Set和Map)转化为数组 格式:Array.from(arrayLike[, mapFn[, thisA ...
- Raising Modulo Numbers(ZOJ 2150)
这题其实就是快速求一个高次幂的模. 这是题目的答案 #include<iostream> #include<cmath> using namespace std; ]; ]; ...
- js 把字符串变成函数
js 把字符串变成函数 eval("(" + fieldEventss[1]+")");
- 2018宁夏邀请赛G(DFS,动态规划【VECTOR<PAIR>】)
//代码跑的很慢四秒会超时,结尾附两秒代码(标程) #include<bits/stdc++.h>using namespace std;typedef long long ll;cons ...