httpClient post附件

本文介绍如何使用Java的HttpClient库来实现文件的POST上传操作。通过构造一个包含文件和其他参数的多部分实体请求,实现了文件上传的功能,并展示了如何解析服务器响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

引入httpClient-mime.jar包

 

private boolean psotFile(String url, File file) throws Exception {
  HttpClient httpclient = new DefaultHttpClient();
  HttpPost httppost = new HttpPost(url);
  // 一个本地的文件
  FileBody bin = new FileBody(file);
  // 一个字符串
  StringBody comment = new StringBody("测试数据地及司法斯柯达",Charset.forName(HTTP.UTF_8));
  StringBody userId = new StringBody("10000");
  // 多部分的实体
  MultipartEntity multi = new MultipartEntity();
  // 增加
  multi.addPart("gsmsnFile", bin);
  multi.addPart("areaName", comment);
  multi.addPart("uId", userId);
  // 设置
  httppost.setEntity(multi);
  System.out.println("执行: " + httppost.getRequestLine());
  HttpResponse response = httpclient.execute(httppost);
  HttpEntity resEntity = response.getEntity();
  System.out.println(response.getStatusLine());
  if (resEntity != null) {
   String jsonStr = EntityUtils.toString(resEntity, HTTP.UTF_8);
   System.out.println("返回长度: " + resEntity.getContentLength());
   System.out.println("返回字符串:" + jsonStr);
  }
  if (resEntity != null) {
   resEntity.consumeContent();
  }
  httpclient.getConnectionManager().shutdown();
  return true;
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值