CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(HOST_NAME, PORT),
new UsernamePasswordCredentials(USER_NAME, TOKEN));
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.build();
try {
HttpPost httpPost = new HttpPost(BASE_URL + EMAIL_API_NAME);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("attachment", new File("D:/opt/test.pdf"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
builder.addTextBody("from", FROM_ADDRESS, ContentType.APPLICATION_JSON);
builder.addTextBody("to", toEmail, ContentType.APPLICATION_JSON);
builder.addTextBody("bcc", bcc, ContentType.APPLICATION_JSON);
builder.addTextBody("subject", subject, ContentType.APPLICATION_JSON);
builder.addTextBody("html", this.loadTemplate(template, values), ContentType.APPLICATION_JSON);
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
CloseableHttpResponse response2 = httpclient.execute(httpPost);
log.info(response2.toString());
try {
System.out.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity2);
} finally {
response2.close();
}
} finally {
httpclient.close();
}
ref:
http://stackoverflow.com/questions/1378920/how-can-i-make-a-multipart-form-data-post-request-using-java