閱讀655 返回首頁    go 阿裏雲 go 技術社區[雲棲]


HttpClient PostMethod模擬帶文件上傳+普通字段的http請求(可解決文件為網絡文件的問題)

代碼示例:

postMethod = new PostMethod("https://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))


最後更新:2017-04-03 22:31:03

  上一篇:go MongoDB單機, 主從, 分布式部署
  下一篇:go 杭電1003