2009年5月7日 星期四

apache commons httpclient 送出 multipart post 寫法

public byte[] uploadMessage(File fileToUpload, UPLOAD_FILE_TYPE type, int[] messageIds) {
byte[] response = null;
try {
// new method
PostMethod postHttpMethod = new PostMethod(webappUrl + uploadFileUrl);
// prepare
// key-value part
Part fileNamePart = new StringPart("fileName", fileToUpload.getName(), "UTF-8");
Part typePart = new StringPart("type", type.toString(), "UTF-8");
StringBuffer strbuf = new StringBuffer();
for (int i = 0; i < messageIds.length; i++) {
strbuf.append(messageIds[i]);
if (i != messageIds.length) {
strbuf.append(",");
}
}
Part messageIdsPart = new StringPart("messageIds", strbuf.toString(), "UTF-8");
// file part
Part filePart = new FilePart("content", fileToUpload);
// multipart
Part[] parts = new Part[] { fileNamePart, typePart, messageIdsPart, filePart };
MultipartRequestEntity multipartEntity = new MultipartRequestEntity(parts, postHttpMethod.getParams());
postHttpMethod.setRequestEntity(multipartEntity);
// execute
try {
httpclient.executeMethod(httpMethod);
response = httpMethod.getResponseBody();
} catch (HttpException e) {
log.error(e.getMessage(), e);
} catch (IOException e) {
log.error(e.getMessage(), e);
} finally {
httpMethod.releaseConnection();
}
return response;
} catch (FileNotFoundException e) {
log.error(e.getMessage(), e);
}
return response;
}

沒有留言: