HttpClient如何进行文件上传呢?
作者:互联网
转自:
http://www.java265.com/JavaCourse/202204/2938.html
HttpClient是一个java语言编写的包,
我们使用HttpClient可以非常方便的发送Http请求
它使基于Http协议请求内容变得非常简单
HttpClient是Apache Jakarta Common下的子项目 它里面封装了很多使用http协议访问的工具,可用于高效访问http
下文笔者讲述基于HttpClient Utils工具类编写一个文件上传的示例分享,如下所示:
HttpClient Utils进行表单进行文件上传的示例分享,如下所示 实现思路: 1.获取连接 2.声明一个HttpPost 3.创建上传体FileBody 4.定义一个HttpEntity传送文件 5.execute执行上传操作 6.获取返回信息 7.关闭连接
/** * 上传文件 */ public void upload() { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost("http://java265.com/uploadFile"); FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg")); StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN); HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build(); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); } EntityUtils.consume(resEntity); } finally { response.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } }
标签:文件,resEntity,System,httppost,println,上传,HttpClient 来源: https://www.cnblogs.com/java265/p/16482777.html