httpClient post附件

引入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;
 }

你可能感兴趣的:(httpclient)