随笔 - 0, 文章 - 264, 评论 - 170, 引用 - 0
数据加载中……

HttpClient PostMethod模拟带文件上传+普通字段的http请求(可解决文件为网络文件的问题)

代码示例:
postMethod = new PostMethod("http://api.t.sina.com.cn/statuses/upload.xml");
Part[] parts 
= {new StringPart("source""695132533"), new StringPart("status", URLEncoder.encode(status, "utf-8")), new FilePart("pic", new File("1.jpg"))};
postMethod.setRequestEntity(
new MultipartRequestEntity(parts, postMethod.getParams()));

上例中,MultipartRequestEntity封装了普通字段和文件字段。

另注:由于自己的应用中,文件块不是在本地的,而是来源于网络,所以FilePart的创建,改为以下代码:
URL url = new URL(picUrl);
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
/**  这么写不对
int length = is.available();
byte[] buffer = new byte[length];
is.read(buffer);
*/

//应该这样写
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = 0;
byte[] b = new byte[1024];
while ((len = is.read(b, 0, b.length)) != -1) {
    baos.write(b, 0, len);
}
byte[] buffer =  baos.toByteArray();
new
 FilePart("pic"new ByteArrayPartSource("pic", buffer))

posted on 2011-01-19 13:55 小一败涂地 阅读(6054) 评论(1)  编辑  收藏 所属分类: 开源工具、插件相关

评论

# re: HttpClient PostMethod模拟带文件上传+普通字段的http请求(可解决文件为网络文件的问题)[未登录]  回复  更多评论   

new FilePart("pic", new ByteArrayPartSource("pic", buffer))

如果new ByteArrayPartSource(文件名, buffer)) 文件名为中文会出现乱码问题。
2013-06-06 13:53 | test

只有注册用户登录后才能发表评论。


网站导航: