代码示例:
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))