禁止转载,如需转载请联系本人
1)简介:
HttpClient是apache的开源项目,弥补了Java自带的URLConnection功能不足,操作繁琐的缺点。
2)简单使用:
a)get方式请求
1 /** 2 * 发送get请求,get表单提交 3 * 获取数返回的json数据 4 */ 5 @Test 6 public void httpGet() { 7 8 //创建httpClient对象 9 HttpClient httpClient = HttpClients.createDefault();//4.3之后的都采用该方法生成httpClient对象 10 //创建url 11 String url = "http://localhost:8080/day29_struts/dataconvert?user.name=yyq&user.age=20&user.birthday=2012-8-9"; 12 //创建httpGet对象 13 HttpGet httpget = new HttpGet(url); 14 System.out.println("URI:" + httpget.getURI()); 15 System.out.println("requestLine:" + httpget.getRequestLine()); 16 17 try { 18 19 //执行get请求 20 HttpResponse response = httpClient.execute(httpget); 21 22 //打印响应状态 23 System.out.println("响应状态:" + response.getStatusLine()); 24 25 //获取响应体 26 HttpEntity entity = response.getEntity(); 27 if (entity != null) { 28 //打印响应内容长度 29 System.out.println("内容长度:" + entity.getContentLength()); 30 //打印响应类型 31 System.out.println("返回类型:" + entity.getContentType()); 32 //响应体内容 33 System.out.println("实体内容:" + EntityUtils.toString(entity)); 34 35 } 36 37 } catch (ClientProtocolException e) { 38 e.printStackTrace(); 39 } catch (IOException e) { 40 e.printStackTrace(); 41 } 42 43 }
结果:
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方式提交(表单提交推荐使用,编码好处理,而且请求数据没有限制)
1 /** 2 * 推荐方式 3 * 发送post请求,即表单post提交 4 */ 5 @Test 6 public void httpPost() { 7 //创建HttpClient实例 8 HttpClient httpClient = HttpClients.createDefault(); 9 //URL 10 String url = "http://localhost:8080/test/TestServlet"; 11 //获取HttpPost实例 12 HttpPost httpPost = new HttpPost(url); 13 System.out.println(httpPost.getRequestLine()); 14 15 try { 16 //设置post请求参数 17 List<NameValuePair> params = new ArrayList<NameValuePair>(); 18 params.add(new BasicNameValuePair("id", "10")); 19 params.add(new BasicNameValuePair("name", "yyq")); 20 //把参数装进post请求体 21 httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8")); 22 23 //获取response实例 24 HttpResponse response = httpClient.execute(httpPost); 25 26 //响应状态 27 System.out.println(response.getStatusLine()); 28 29 //获取响应体 30 HttpEntity entity = response.getEntity(); 31 32 if (entity != null) { 33 34 System.out.println(EntityUtils.toString(entity, "utf-8")); 35 36 } 37 38 } catch (ClientProtocolException e) { 39 e.printStackTrace(); 40 } catch (IOException e) { 41 e.printStackTrace(); 42 } 43 44 }
结果:
POST http://localhost:8080/test/TestServlet HTTP/1.1
HTTP/1.1 200 OK
c)文件上传与下载
服务器端(采用tomcat)
1 package servlet; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.util.List; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 12 import org.apache.commons.fileupload.FileItem; 13 import org.apache.commons.fileupload.FileUploadException; 14 import org.apache.commons.fileupload.disk.DiskFileItemFactory; 15 import org.apache.commons.fileupload.servlet.ServletFileUpload; 16 17 public class UploadServlet extends HttpServlet { 18 19 public void doGet(HttpServletRequest request, HttpServletResponse response) 20 throws ServletException, IOException { 21 22 request.setCharacterEncoding("utf-8"); 23 response.setContentType("text/html;charset=utf-8"); 24 25 //检测是不是存在上传文件,如果不存在则按一般方式解决 26 boolean isMultipart = ServletFileUpload.isMultipartContent(request); 27 if (isMultipart) { 28 29 try { 30 DiskFileItemFactory factory = new DiskFileItemFactory(); 31 //指定在内存中缓存数据大小,单位为byte,这里设为1Mb 32 factory.setSizeThreshold(1024*1024); 33 //设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录 ,老提示找不到路径,气得要死,无奈注释掉用tomcat自带的temp目录 34 //factory.setRepository(new File(getServletContext().getRealPath("uploadFile/tem"))); 35 36 //实例化文件上传对象 37 ServletFileUpload upload = new ServletFileUpload(factory); 38 //设置单个文件最大限制 39 upload.setFileSizeMax(500*1024*1024); 40 //设置总文件限制 41 upload.setSizeMax(200*1024*1024); 42 //设置编码 43 upload.setHeaderEncoding("utf-8"); 44 //设置监视器,显示上传进度 45 46 //解析请求 47 List<FileItem> items = upload.parseRequest(request); 48 //解析表单 49 if (items != null) { 50 System.out.println(items.size()); 51 52 for (FileItem fileItem : items) { 53 54 //如果是普通表单格式 55 if (fileItem.isFormField()) { 56 57 response.getWriter().print("---普通文本内容---"); 58 System.out.println("文本类型:" + fileItem.getContentType()); 59 System.out.println("表单属性名:" + fileItem.getFieldName()); 60 System.out.println("表单值:" + fileItem.getString("utf-8")); 61 62 } else { 63 64 System.out.println("表单属性名:" + fileItem.getFieldName()); 65 //上传的文件名 66 String fileName = fileItem.getName(); 67 //把文件写在当前应用的upload目录 68 String basePath = getServletContext().getRealPath("/upload"); 69 fileItem.write(new File(basePath, fileName)); 70 //删除缓存区 71 fileItem.delete(); 72 73 } 74 75 } 76 77 } 78 79 } catch (FileUploadException e) { 80 e.printStackTrace(); 81 } catch (Exception e) { 82 e.printStackTrace(); 83 } 84 85 } else { 86 87 } 88 89 } 90 91 @Override 92 protected void doPost(HttpServletRequest req, HttpServletResponse resp) 93 throws ServletException, IOException { 94 doGet(req, resp); 95 } 96 97 }
客户端:
1 /** 2 * 上传文件,post方式 3 * 包含普通内容和上传的文件 4 */ 5 @Test 6 public void fileUpload() { 7 8 HttpClient httpClient = HttpClients.createDefault(); 9 10 String url = "http://localhost:8080/test/UploadServlet"; 11 HttpPost httpPost = new HttpPost(url); 12 13 14 /** 15 * 封装到HttpEneity中 16 * 使用MultipartEntityBuilder.create().build()生成该对象 17 * 原来的new MultipartEntity()已废弃 18 * 19 * 封装请求体的两种方式: 20 * 1,可以创建StringBody和FileBody封装文本和文件 21 * 2,直接使用MultipartEntityBuilder.create() 22 * 的addBinaryBody(name, File)封装文件 23 * addTextBody(name, text, ContentType)封装文本 24 */ 25 //普通数据的封装 26 StringBody sb = new StringBody("yyq", 27 ContentType.create("text/plain", "utf-8")); 28 29 //文件封装 30 FileBody fb = new FileBody(new File("E:/App/CodeBlocks.zip")); 31 HttpEntity reqEntity = MultipartEntityBuilder.create() 32 // .addPart("name", sb) 33 .addTextBody("name", "yyq2", ContentType.create("text/plain", "utf-8")) 34 // .addPart("file", fb) 35 .addBinaryBody("name", new File("E:/App/CodeBlocks.zip")) 36 .build(); 37 38 //4,请求体封装到post中 39 httpPost.setEntity(reqEntity); 40 41 try { 42 HttpResponse response = httpClient.execute(httpPost); 43 44 HttpEntity entity = response.getEntity(); 45 46 if (response.getStatusLine().getStatusCode() == 200) { 47 System.out.println(EntityUtils.toString(entity, "utf-8")); 48 } 49 50 } catch (ClientProtocolException e) { 51 e.printStackTrace(); 52 } catch (IOException e) { 53 e.printStackTrace(); 54 } 55 56 }
附:HTTPUtils,同步方式,异步还是okhttp吧
1 public class HttpClientUtil { 2 3 public static String doGet(String url, Map<String, String> param) { 4 5 // 创建Httpclient对象 6 CloseableHttpClient httpclient = HttpClients.createDefault(); 7 8 String resultString = ""; 9 CloseableHttpResponse response = null; 10 try { 11 // 创建uri 12 URIBuilder builder = new URIBuilder(url); 13 if (param != null) { 14 for (String key : param.keySet()) { 15 builder.addParameter(key, param.get(key)); 16 } 17 } 18 URI uri = builder.build(); 19 20 // 创建http GET请求 21 HttpGet httpGet = new HttpGet(uri); 22 23 // 执行请求 24 response = httpclient.execute(httpGet); 25 // 判断返回状态是否为200 26 if (response.getStatusLine().getStatusCode() == 200) { 27 resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); 28 } 29 } catch (Exception e) { 30 e.printStackTrace(); 31 } finally { 32 try { 33 if (response != null) { 34 response.close(); 35 } 36 httpclient.close(); 37 } catch (IOException e) { 38 e.printStackTrace(); 39 } 40 } 41 return resultString; 42 } 43 44 public static String doGet(String url) { 45 return doGet(url, null); 46 } 47 48 public static String doPost(String url, Map<String, String> param) { 49 // 创建Httpclient对象 50 CloseableHttpClient httpClient = HttpClients.createDefault(); 51 CloseableHttpResponse response = null; 52 String resultString = ""; 53 try { 54 // 创建Http Post请求 55 HttpPost httpPost = new HttpPost(url); 56 // 创建参数列表 57 if (param != null) { 58 List<NameValuePair> paramList = new ArrayList<>(); 59 for (String key : param.keySet()) { 60 paramList.add(new BasicNameValuePair(key, param.get(key))); 61 } 62 // 模拟表单 63 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList); 64 httpPost.setEntity(entity); 65 } 66 // 执行http请求 67 response = httpClient.execute(httpPost); 68 resultString = EntityUtils.toString(response.getEntity(), "utf-8"); 69 } catch (Exception e) { 70 e.printStackTrace(); 71 } finally { 72 try { 73 response.close(); 74 } catch (IOException e) { 75 // TODO Auto-generated catch block 76 e.printStackTrace(); 77 } 78 } 79 80 return resultString; 81 } 82 83 public static String doPost(String url) { 84 return doPost(url, null); 85 } 86 87 public static String doPostJson(String url, String json) { 88 // 创建Httpclient对象 89 CloseableHttpClient httpClient = HttpClients.createDefault(); 90 CloseableHttpResponse response = null; 91 String resultString = ""; 92 try { 93 // 创建Http Post请求 94 HttpPost httpPost = new HttpPost(url); 95 // 创建请求内容 96 StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); 97 httpPost.setEntity(entity); 98 // 执行http请求 99 response = httpClient.execute(httpPost); 100 resultString = EntityUtils.toString(response.getEntity(), "utf-8"); 101 } catch (Exception e) { 102 e.printStackTrace(); 103 } finally { 104 try { 105 response.close(); 106 } catch (IOException e) { 107 // TODO Auto-generated catch block 108 e.printStackTrace(); 109 } 110 } 111 112 return resultString; 113 } 114 }