用的工具包是package org.apache.commons.httpclient
参数说明url是地址,第二个map是请求body,第三个是文件对象,第四个是请求头参数
/**
* http请求上传文件
* @param url
* @param map
* @param file
* @param head
* @return
*/
public static String doPostWithFile(String url, Map<String,String> map, File file,Map<String,String> head) {
try
{
PostMethod post = new PostMethod(url);
FilePart fp = new FilePart("file",file);
fp.setCharSet("utf-8");
StringPart stringPart;
Part[] parts = new Part[map.size()+1];
int i = 0;
for(Map.Entry<String, String> m : map.entrySet()){
stringPart = new StringPart(m.getKey(),m.getValue(),"UTF-8");
parts[i] = stringPart;
i++;
}
parts[parts.length-1]=fp;
MultipartRequestEntity entity = new MultipartRequestEntity(parts, new HttpMethodParams());
post.setRequestEntity(entity);
for(Map.Entry<String, String> m : head.entrySet()){
post.setRequestHeader(m.getKey(),m.getValue());
}
client.executeMethod(post);
return post.getResponseBodyAsString();
} catch (Exception e){
log.error("doPostWithFile occur a exception", e);
return null;
}
}