我编写了一个小助手方法,将 Multipart POST 支持添加到 AppEngine(使用 Apache HTTP 客户端库)。
public static void addMultipartBodyToRequest(MultipartEntity entity, HTTPRequest req) throws IOException{
/*
* turn Entity to byte[] using ByteArrayOutputStream
*/
ByteArrayOutputStream bos = new ByteArrayOutputStream();
entity.writeTo(bos);
byte[] body = bos.toByteArray();
/*
* extract multipart boundary (body starts with --boundary\r\n)
*/
String boundary = new BufferedReader(new StringReader(new String(body))).readLine();
boundary = boundary.substring(2, boundary.length());
/*
* add multipart header and body
*/
req.addHeader(new HTTPHeader("Content-type", "multipart/form-data; boundary=" + boundary));
req.setPayload(body);
}
调用代码如下所示:
MultipartEntity e = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
e.addPart("part1", new StringBody("value1"));
e.addPart("part2", new StringBody("value2"));
HTTPRequest req = new HTTPRequest(new URL(myUrl), HTTPMethod.POST);
ServletHelper.addMultipartBodyToRequest(e, req);
URLFetchServiceFactory.getURLFetchService().fetchAsync(req);