使用MultipartEntityBuilder上传文件

时间:2017-07-25 21:40:44

标签: java file-upload apache-httpclient-4.x

我有一些现有的Java代码将文件(作为字节数组)上传到Box.net,最近我认为将代码升级到Apache HttpClient 4.4会很好。然而,事实证明这比预期的要困难一些。这是我的遗留代码:

HttpPost postMethod = new HttpPost(url);
MultipartEntity multipartEntity = new MultipartEntity();
for (NameValuePair parameter : parameters) {
    String parameterName = parameter.getName();
    String parameterValue = parameter.getValue();
    StringBody valueBody = new StringBody(parameterValue, ContentType.MULTIPART_FORM_DATA);                    
    multipartEntity.addPart(parameterName, valueBody);
}

Iterator iterator = byteArrayHashMap.keySet().iterator();
while (iterator.hasNext()) {
    String key = (String) iterator.next();
    byte[] byteArray = byteArrayHashMap.get(key);
    multipartEntity.addPart(key, new ByteArrayBody(byteArray, key));
}

postMethod.setEntity(multipartEntity);

这是新代码:

HttpPost postMethod = new HttpPost(url);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
for (NameValuePair parameter : parameters) {
    String parameterName = parameter.getName();
    String parameterValue = parameter.getValue();
    StringBody valueBody = new StringBody(parameterValue, ContentType.MULTIPART_FORM_DATA);                    
    multipartEntityBuilder.addPart(parameterName, valueBody);
}

Iterator iterator = byteArrayHashMap.keySet().iterator();
while (iterator.hasNext()) {
    String key = (String) iterator.next();
    byte[] byteArray = byteArrayHashMap.get(key);
    multipartEntityBuilder.addBinaryBody(key, byteArray);
}

postMethod.setEntity(multipartEntityBuilder.build());

当我运行新代码时,服务器会抱怨缺少参数。我正确使用MultipartEntityBuilder吗?

1 个答案:

答案 0 :(得分:0)

如果有人遇到这个问题,我可以通过更新addBinaryBody调用来设置ContentType,如下所示:multipartEntityBuilder.addBinaryBody(key,byteArray,ContentType.DEFAULT_BINARY,key);