这里直接贴出的是我封装好的doPostFile方法,httpclient 的版本是3.1。
public static String doPostFile(String url, Part[] parts){
String response = null;
PostMethod postMethod = new PostMethod(url);
try{
//设置请求实体
postMethod.setRequestEntity(new MultipartRequestEntity(parts,postMethod.getParams()));
HttpClient client = new HttpClient();
//设置连接超时限度
client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
client.executeMethod(postMethod);
if(postMethod.getStatusCode() == HttpStatus.SC_OK){
response = new String(postMethod.getResponseBodyAsString().getBytes("utf-8"));
}
} catch(Exception e){
LOGGER.error("HttpServiceSender.doPostFile()",e.getMessage());
} finally {
postMethod.releaseConnection();
}
return response;
}
调用此方法的代码,注意参数的传递方式
public String uploadImage(File file,String id,String name){
String result = null;
try{
//文件part,new FilePart添加的是File类型的文件,后面StringPart则为字符串参数
Part[] parts = { new FilePart("file", file),
new StringPart("id", id),
new StringPart("id",name)};
result = HttpServiceSender.doPostFile(SERVER+"service/resource/upload",parts);
}catch(Exception e){
Logger.error("ImageService.uploadImage()", e.getMessage());
}
return result;
}
分享到:
相关推荐
HttpClient实现POST GET和文件下载 HttpClient实现POST GET和文件下载
用HttpClient实现文件下载需要满足:有一台web服务器,要下载的源文件需存放在web服务器的特定目录下。通过发起http请求实现文件下载功能。
使用HttpClient实现文件的上传所需lib
文档中详细演示了如何使用HttpClient4进行文件上传
关闭HttpClient日志的logback文件
文件上传 HttpClient
Eclipse下完整的java程序,包含HttpClient的全部jar包。通过java类文件,实现通过链接将文件下载本地
httpclient3 httpclient4 上传文件 乱码问题
httpclient和RestfuL服务风格上传下载文件,可改为JAVA分布式系统进行交互,具体用法和改法详见代码里的注释
使用httpclient上传文件, CloseableHttpClient httpClient = HttpClientBuilder.create().build();
本功能支持文件上传 下载,支持请求流,支持JSON、XML请求,本版本是httpclient 4,其它jar包自行下载
该工具类使用httpclient进行http or https请求,包括requestbody格式和form表单格式,另外含文件服务器中转上传方法,几乎支持所有常用接口调用,内含详细注释和说明文件,含jar包,及maven方式引用,拿过去直接用吧
HttpClient Post提交多文件及多个普通参数,已经封装成工具类。 需传入 要请求的url 普通参数map 例 map.put("param1","张三"); 需要传入的文件流map 其中key为文件名 服务端接收无乱码。
Android使用HttpClient实现上传下载功能并监控进度
Android 使用HttpClient和第三方MiME文件上传类库,实现文件上传带进度条。 注:这个是自己写的,亲测没有问题。
NULL 博文链接:https://wangwang-163-com.iteye.com/blog/728831
httpClient上传文件,能直接运行的代码,appache commons
HttpClient 上传文件 Servlet 处理文件上传 commons-fileupload 处理文件上传 commons-fileupload 处理文件上传,在struts中可以不用对应actionform,在jsp,servelet中应用都很方便