HttpClient PostMethod模擬帶文件上傳+普通字段的http請求(可解決文件為網(wǎng)絡(luò)文件的問題)
代碼示例:
上例中,MultipartRequestEntity封裝了普通字段和文件字段。
另注:由于自己的應(yīng)用中,文件塊不是在本地的,而是來源于網(wǎng)絡(luò),所以FilePart的創(chuàng)建,改為以下代碼:
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()));
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封裝了普通字段和文件字段。
另注:由于自己的應(yīng)用中,文件塊不是在本地的,而是來源于網(wǎng)絡(luò),所以FilePart的創(chuàng)建,改為以下代碼:
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);
*/
//應(yīng)該這樣寫
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))
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
/** 這么寫不對
int length = is.available();
byte[] buffer = new byte[length];
is.read(buffer);
*/
//應(yīng)該這樣寫
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 小一敗涂地 閱讀(6099) 評論(1) 編輯 收藏 所屬分類: 開源工具、插件相關(guān)