httpclient 上传、下载文件,美团Android研发岗二面

  1. // 把一个普通参数和文件上传给下面这个地址 是一个servlet

  2. HttpPost httpPost = new HttpPost(

  3. “http://localhost:8080/xxx/xxx.action”);

  4. // 把文件转换成流对象FileBody

  5. File file = new File(filePath);

  6. FileBody bin = new FileBody(file);

  7. StringBody uploadFileName = new StringBody(

  8. “把我修改成文件名称”, ContentType.create(

  9. “text/plain”, Consts.UTF_8));

  10. //以浏览器兼容模式运行,防止文件名乱码。

  11. HttpEntity reqEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)

  12. .addPart(“uploadFile”, bin) //uploadFile对应服务端类的同名属性<File类型>

  13. .addPart(“uploadFileName”, uploadFileName)//uploadFileName对应服务端类的同名属性<String类型>

  14. .setCharset(CharsetUtils.get(“UTF-8”)).build();

  15. httpPost.setEntity(reqEntity);

  16. System.out.println("发起请求的页面地址 " + httpPost.getRequestLine());

  17. // 发起请求 并返回请求的响应

  18. CloseableHttpResponse response = httpClient.execute(httpPost);

  19. try {

  20. System.out.println("----------------------------------------");

  21. // 打印响应状态

  22. System.out.println(response.getStatusLine());

  23. // 获取响应对象

  24. HttpEntity resEntity = response.getEntity();

  25. if (resEntity != null) {

  26. // 打印响应长度

《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》

开源分享完整内容戳这里

System.out.println("Response content length: "

  1. + resEntity.getContentLength());

  2. // 打印响应内容

  3. System.out.println(EntityUtils.toString(resEntity,

  4. Charset.forName(“UTF-8”)));

  5. }

  6. // 销毁

  7. EntityUtils.consume(resEntity);

  8. } finally {

  9. response.close();

  10. }

  11. } finally {

  12. httpClient.close();

  13. }

  14. }

  15. /**

  16. * 下载文件

  17. * @param url            http://www.xxx.com/img/333.jpg

  18. * @param destFileName   xxx.jpg/xxx.png/xxx.txt

  19. * @throws ClientProtocolException

  20. * @throws IOException

  21. */

  22. public static void getFile(String url, String destFileName)

  23. throws ClientProtocolException, IOException {

  24. // 生成一个httpclient对象

  25. CloseableHttpClient httpclient = HttpClients.createDefault();

  26. HttpGet httpget = new HttpGet(url);

  27. HttpResponse response = httpclient.execute(httpget);

  28. HttpEntity entity = response.getEntity();

  29. InputStream in = entity.getContent();

  30. File file = new File(destFileName);

  31. try {

  32. FileOutputStream fout = new FileOutputStream(file);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值