HttpClient上传文件

折腾了一下用HttpClient上传文件,主要是不需要设置“multipart/form-data”,否则会出现“the request was rejected because no multipart boundary was found”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
PostMethod method = new PostMethod(url);
  Part[] part = new Part[params.size()+1];
    Set<String> keySet = params.keySet();
    int i=0;
    for(String key : keySet) {
      String value = params.get(key);
      if(StringUtil.isNotNull(value)){
          part[i] = new StringPart(key, value, "UTF-8");
      }else{
          part[i] = new StringPart(key, "", "UTF-8");
      }
      i++;
    }
    FilePart fp = new  FilePart("image", file);
    fp.setContentType(MIME.ENC_BINARY);
    part[i] = fp;
    HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
    managerParams.setConnectionTimeout(3000000);
     managerParams.setSoTimeout(12000000);
    int statusCode;
  try {
        MultipartRequestEntity mrp= new  MultipartRequestEntity(part, method.getParams());
        method.setRequestEntity(mrp);
        statusCode = httpClient.executeMethod(method);
      if(statusCode != HttpStatus.SC_OK){
          log.error("Method failed code=" + statusCode + ": " + method.getStatusLine());
        }else{
          InputStream inputStream = method.getResponseBodyAsStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            String str= "";
            while((str = br.readLine()) != null){
              response .append(str);
            }
        }
  } catch (HttpException e) {
      log.error(e.getMessage(), e);
  } catch (IOException e) {
      log.error(e.getMessage(), e);
  } finally{
      method.releaseConnection();
  }