HttpClient PostMethod模擬帶文件上傳+普通字段的http請求(一樣適用於網絡文件

代碼示例:java

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的建立,改成如下代碼:
api

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));
相關文章
相關標籤/搜索