要补充@Pablo 所说的内容,如果您已经在使用 Apache Commons HTTP 客户端库,则可以使用您的MultipartEntity
对象来处理多部分请求格式:
MultipartEntity reqEntity = new MultipartEntity();
// add your ContentBody fields as normal...
// Now, pull out the contents of everything you've added and set it as the payload
ByteArrayOutputStream bos = new ByteArrayOutputStream((int)reqEntity.getContentLength());
reqEntity.writeTo(bos);
oAuthReq.addPayload(bos.toByteArray());
// Finally, set the Content-type header (with the boundary marker):
Header contentType = reqEntity.getContentType();
oAuthReq.addHeader(contentType.getName(), contentType.getValue());
// Sign and send like normal:
service.signRequest(new Token(oAuthToken, oAuthSecret), oAuthReq);
Response oauthResp = oAuthReq.send();
当然,这样做的缺点是您需要将整个内容主体读入byte[]
内存中,因此如果您要发送巨大的文件,这可能不是最佳选择。但是,对于小型上传,这对我有用。