禁止转载,如需转载请联系本人

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的使用的更多相关文章

  1. Atitit 类库冲突解决方案  httpclient-4.5.2.jar

    Atitit 类库冲突解决方案  httpclient-4.5.2.jar 错误提示如下1 版本如下(client and selenium)2 解决流程2 挂载源码 (SSLConnectionSo ...

  2. httpclient4.3.6/httpcore-4.4自己封装的工具类

    引入jar包 httpclient4.3.6/httpcore-4.4 package com.develop.util; import java.io.IOException; import jav ...

  3. httpclient4.3 工具类

    httpclient4.3  java工具类. .. .因项目须要开发了一个工具类.正经常常使用的httpclient 请求操作应该都够用了 工具类下载地址:http://download.csdn. ...

  4. HttpClient4.0

    ****************************HttpClient4.0用法***************************** 1.初始化HttpParams,设置组件参数 //Ht ...

  5. [置顶] android网络通讯之HttpClient4不指定参数名发送Post

    在HttpClient4之前都是通过List<NameValuePair>键值对的形式来向服务器传递参数 ,在4.0版本中在加入了不指定参数名发送数据的形式,利用StringEntity来 ...

  6. HttpClient4的使用,模拟浏览器登陆新浪微博,发表微博和文字+图片微博

    HttpClient4,最原始的需求就是使用其来模拟浏览器想服务器发起http请求,当然,他的功能不止于此,但是我需要的就是这个功能而已,jdk也有其自带的类似的api:UrlConnection,效 ...

  7. HttpClient4.5 post请求xml到服务器

    1.加入HttpClient4.5和junit依赖包 <dependencies> <dependency> <groupId>org.apache.httpcom ...

  8. Java模拟http上传文件请求(HttpURLConnection,HttpClient4.4,RestTemplate)

    先上代码: public void uploadToUrl(String fileId, String fileSetId, String formUrl) throws Throwable { St ...

  9. 使用HttpClient4.5实现HTTPS的双向认证

    说明:本文主要是在平时接口对接开发中遇到的为保证传输安全的情况特要求使用https进行交互的情况下,使用httpClient4.5版本对HTTPS的双向验证的  功能的实现    首先,老生常谈,文章 ...

  10. HttpClient4.5.2调用示例(转载+原创)

    操作HttpClient时的一个工具类,使用是HttpClient4.5.2 package com.xxxx.charactercheck.utils; import java.io.File; i ...

随机推荐

  1. Python图片识别——人工智能篇

     一.安装pytesseract和PIL PIL全称:Python Imaging Library,python图像处理库,这个库支持多种文件格式,并提供了强大的图像处理和图形处理能力. 由于PIL仅 ...

  2. mybatis 学习四 源码分析 mybatis如何执行的一条sql

    总体三部分,创建sessionfactory,创建session,执行sql获取结果 1,创建sessionfactory      这里其实主要做的事情就是将xml的所有配置信息转换成一个Confi ...

  3. C#设计模式(9)——装饰者模式

    一.概念 装饰者模式以对客户透明的方式动态地给一个对象附加上更多的责任,装饰者模式相比生成子类可以更灵活地增加功能. 二.模型 三.代码实现 /// <summary> /// 手机抽象类 ...

  4. Spring, Hibernate and Oracle Stored Procedures

    一篇英文博文,写的是利用hibernate处理存储过程中的游标等等: Motivation: While there are a few resources available online for ...

  5. 关于UI性能优化

    1.使用已经有的VIEW,而不是每次都去新生成一个 2.创建自定义类来进行组件和数据的缓存,在下一次调用的时候直接从FLAG中取出 3.分页,预加载 使用VIEWSTUB进行调用时加载 VIEWSTU ...

  6. linux-java环境安装以及ssh

    1 下载Java8   http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html 2 使用 ...

  7. Animations使用01 BrowserAnimationsModule

    1 基础知识 1.1 动画 就是从一个状态过渡到另外一个状态 1.2 状态 元素本身的形状.颜色.大小等 1.3 Angular中的动画 给元素添加一个触发器,当这个触发器被触发后就会让该元素的状态发 ...

  8. pig入门教程(2)

    本文可以让刚接触pig的人对一些基础概念有个初步的了解. 本文的大量实例都是作者Darran Zhang(website: codelast.com)在工作.学习中总结的经验或解决的问题,并且添加了较 ...

  9. 阶段2-新手上路\项目-移动物体监控系统\Sprint3-移动监控主系统设计与开发

    移动图像监控系统 去找一些相关开源程序进行移植:百度搜索-linux 移动监控 motion是一套免费开源的移动图像监测程序 前面我们已经使用了很多开源软件,他们的使用方法都是大同小异的 1).先在当 ...

  10. Entity Framework Code-First(10):Fluent API

    Fluent API in Code-First: We have seen different DataAnnotations attributes in the previous sections ...