下面列出了org.apache.http.entity.mime.MultipartEntityBuilder#addTextBody ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void postContent(String url, Map<String, String> data, InputStream is) throws Exception {
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(X_LINE_ACCESS, getAuthToken());
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
for(Map.Entry<String, String> entry : data.entrySet()) {
entityBuilder.addTextBody(entry.getKey(), entry.getValue(), ContentType.APPLICATION_FORM_URLENCODED);
}
// The LINE object storage service doesn't support chunked encoding; therefore,
// we must be able to specify the "Content-Length" header.
// It can be achieved by giving Apache library either a byte array or a File object.
entityBuilder.addBinaryBody("file", IOUtils.toByteArray(is));
httpPost.setEntity(entityBuilder.build());
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_CREATED) {
throw new IOException("Fail to send request to URL " + url + ". Status: " + statusCode);
}
}
HttpEntity getRequestEntity(ContentReader reader, String sourceMimetype, String sourceExtension,
String targetExtension, long timeoutMs, String[] args, StringJoiner sj)
{
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
ContentType contentType = ContentType.create(sourceMimetype);
builder.addBinaryBody("file", reader.getContentInputStream(), contentType, "tmp."+sourceExtension);
builder.addTextBody("targetExtension", targetExtension);
sj.add("targetExtension" + '=' + targetExtension);
for (int i=0; i< args.length; i+=2)
{
if (args[i+1] != null)
{
builder.addTextBody(args[i], args[i + 1]);
sj.add(args[i] + '=' + args[i + 1]);
}
}
if (timeoutMs > 0)
{
String timeoutMsString = Long.toString(timeoutMs);
builder.addTextBody("timeout", timeoutMsString);
sj.add("timeout=" + timeoutMsString);
}
return builder.build();
}
@Test
public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws IOException {
final CloseableHttpClient client = HttpClients.createDefault();
final HttpPost httpPost = new HttpPost(SAMPLE_URL);
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("username", DEFAULT_USER);
builder.addTextBody("password", DEFAULT_PASS);
builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
final HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
final CloseableHttpResponse response = client.execute(httpPost);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
/**
* Posts JSON to a URL
* @param transmissionString
*/
private void publish(String transmissionString)
{
try
{
String iotype = "json";
String fieldName = "json";
String contentType = "application/json";
// String fileName = "filename.graphson";
// upload a GraphSON file
HttpPost httpPost = new HttpPost(apiURL + "/titan");
// byte[] userpass = (userId + ":" + password).getBytes();
// byte[] encoding = Base64.encodeBase64(userpass);
/// httpPost.setHeader("Authorization", "Basic " + new String(encoding));
MultipartEntityBuilder meb = MultipartEntityBuilder.create();
meb.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
meb.addPart("fieldName", new StringBody(fieldName));
meb.addPart("contentType", new StringBody(contentType));
// meb.addPart("name", new StringBody(fileName));
meb.addTextBody("transaction", transmissionString);
// FileBody fileBody = new FileBody(new File("./data/" + fileName));
// meb.addPart(fieldName, fileBody);
httpPost.setEntity(meb.build());
HttpResponse httpResponse = client.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// EntityUtils.consume(httpEntity);
String responseString = EntityUtils.toString(httpEntity, "UTF-8");
System.out.println(responseString);
} catch (Exception e)
{
e.printStackTrace();
}
}
/**
* Sends a voice note using Send Voice method (https://core.telegram.org/bots/api#sendvoice)
* For this to work, your audio must be in an .ogg file encoded with OPUS
* @param sendVoice Information to send
* @return If success, the sent Message is returned
* @throws TelegramApiException If there is any error sending the audio
*/
@Override
public final Message execute(SendVoice sendVoice) throws TelegramApiException {
assertParamNotNull(sendVoice, "sendVoice");
sendVoice.validate();
try {
String url = getBaseUrl() + SendVoice.PATH;
HttpPost httppost = configuredHttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setLaxMode();
builder.setCharset(StandardCharsets.UTF_8);
builder.addTextBody(SendVoice.CHATID_FIELD, sendVoice.getChatId(), TEXT_PLAIN_CONTENT_TYPE);
addInputFile(builder, sendVoice.getVoice(), SendVoice.VOICE_FIELD, true);
if (sendVoice.getReplyMarkup() != null) {
builder.addTextBody(SendVoice.REPLYMARKUP_FIELD, objectMapper.writeValueAsString(sendVoice.getReplyMarkup()), TEXT_PLAIN_CONTENT_TYPE);
}
if (sendVoice.getReplyToMessageId() != null) {
builder.addTextBody(SendVoice.REPLYTOMESSAGEID_FIELD, sendVoice.getReplyToMessageId().toString(), TEXT_PLAIN_CONTENT_TYPE);
}
if (sendVoice.getDisableNotification() != null) {
builder.addTextBody(SendVoice.DISABLENOTIFICATION_FIELD, sendVoice.getDisableNotification().toString(), TEXT_PLAIN_CONTENT_TYPE);
}
if (sendVoice.getDuration() != null) {
builder.addTextBody(SendVoice.DURATION_FIELD, sendVoice.getDuration().toString(), TEXT_PLAIN_CONTENT_TYPE);
}
if (sendVoice.getCaption() != null) {
builder.addTextBody(SendVoice.CAPTION_FIELD, sendVoice.getCaption(), TEXT_PLAIN_CONTENT_TYPE);
if (sendVoice.getParseMode() != null) {
builder.addTextBody(SendVoice.PARSEMODE_FIELD, sendVoice.getParseMode(), TEXT_PLAIN_CONTENT_TYPE);
}
}
HttpEntity multipart = builder.build();
httppost.setEntity(multipart);
return sendVoice.deserializeResponse(sendHttpPostRequest(httppost));
} catch (IOException e) {
throw new TelegramApiException("Unable to send voice", e);
}
}
public static HttpEntity getMultiPartEntity(String fileName, String contentType, InputStream fileStream, Map<String, String> additionalFormFields) throws IOException {
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
if (additionalFormFields != null && !additionalFormFields.isEmpty()) {
for (Entry<String, String> field : additionalFormFields.entrySet()) {
entityBuilder.addTextBody(field.getKey(), field.getValue());
}
}
entityBuilder.addBinaryBody(fileName, IOUtils.toByteArray(fileStream), ContentType.create(contentType), fileName);
return entityBuilder.build();
}
public static HttpEntity createMultipartFormEntity(Map<String, String> parameters, InputStream is) {
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
multipartEntityBuilder.addBinaryBody("file", is, ContentType.create("application/octet-stream"), "file");
for (Entry<String, String> entry : parameters.entrySet()) {
multipartEntityBuilder.addTextBody(entry.getKey(), entry.getValue());
}
return multipartEntityBuilder.build();
}
public static HttpEntity getMultiPartEntity(String fileName, String contentType, InputStream fileStream, Map<String, String> additionalFormFields) throws IOException {
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
if (additionalFormFields != null && !additionalFormFields.isEmpty()) {
for (Entry<String, String> field : additionalFormFields.entrySet()) {
entityBuilder.addTextBody(field.getKey(), field.getValue());
}
}
entityBuilder.addBinaryBody(fileName, IOUtils.toByteArray(fileStream), ContentType.create(contentType), fileName);
return entityBuilder.build();
}
private HttpRequestBase getHttpRequest() throws URISyntaxException, UnsupportedEncodingException {
if (!route.isEmpty()) {
String path = urlBuilder.getPath() + route;
path = path.replace("//", "/");
urlBuilder.setPath(path);
}
request.setURI(urlBuilder.build());
if (request instanceof HttpPost) {
if (fileParam != null) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
for (NameValuePair formParam : formParams) {
builder.addTextBody(formParam.getName(), formParam.getValue());
}
HttpEntity entity = builder
.addBinaryBody(fileParam, fileBytes, ContentType.MULTIPART_FORM_DATA, fileName)
.build();
((HttpPost) request).setEntity(entity);
} else if (!formParams.isEmpty()) {
((HttpPost) request).setEntity(new UrlEncodedFormEntity(formParams));
}
} else if (request instanceof HttpPut) {
if (!formParams.isEmpty()) {
((HttpPut) request).setEntity(new UrlEncodedFormEntity(formParams));
}
}
return request;
}
@Override
public List<Message> execute(SendMediaGroup sendMediaGroup) throws TelegramApiException {
assertParamNotNull(sendMediaGroup, "sendMediaGroup");
sendMediaGroup.validate();
try {
String url = getBaseUrl() + SendMediaGroup.PATH;
HttpPost httppost = configuredHttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setLaxMode();
builder.setCharset(StandardCharsets.UTF_8);
builder.addTextBody(SendMediaGroup.CHATID_FIELD, sendMediaGroup.getChatId(), TEXT_PLAIN_CONTENT_TYPE);
addInputData(builder, sendMediaGroup.getMedia(), SendMediaGroup.MEDIA_FIELD);
if (sendMediaGroup.getDisableNotification() != null) {
builder.addTextBody(SendMediaGroup.DISABLENOTIFICATION_FIELD, sendMediaGroup.getDisableNotification().toString(), TEXT_PLAIN_CONTENT_TYPE);
}
if (sendMediaGroup.getReplyToMessageId() != null) {
builder.addTextBody(SendMediaGroup.REPLYTOMESSAGEID_FIELD, sendMediaGroup.getReplyToMessageId().toString(), TEXT_PLAIN_CONTENT_TYPE);
}
HttpEntity multipart = builder.build();
httppost.setEntity(multipart);
return sendMediaGroup.deserializeResponse(sendHttpPostRequest(httppost));
} catch (IOException e) {
throw new TelegramApiException("Unable to set chat photo", e);
}
}
/**
* Encodes multipart/form-data where the body content must be an instance of the {@link MultipartContent} class. Individual parts will be
* encoded using the encoders available to the {@link ChainedHttpConfig} object.
*
* @param config the chained configuration object
* @param ts the server adapter
*/
public static void multipart(final ChainedHttpConfig config, final ToServer ts) {
try {
final ChainedHttpConfig.ChainedRequest request = config.getChainedRequest();
final Object body = request.actualBody();
if (!(body instanceof MultipartContent)) {
throw new IllegalArgumentException("Multipart body content must be MultipartContent.");
}
final String contentType = request.actualContentType();
if (!(contentType.equals(MULTIPART_FORMDATA.getAt(0)) || contentType.equals(MULTIPART_MIXED.getAt(0)))) {
throw new IllegalArgumentException("Multipart body content must be multipart/form-data.");
}
final String boundary = randomString(10);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().setBoundary(boundary);
final String boundaryContentType = "multipart/form-data; boundary=" + boundary;
entityBuilder.setContentType(ContentType.parse(boundaryContentType));
for (final MultipartContent.MultipartPart mpe : ((MultipartContent) body).parts()) {
if (mpe.getFileName() == null) {
entityBuilder.addTextBody(mpe.getFieldName(), (String) mpe.getContent());
} else {
final byte[] encodedBytes = EmbeddedEncoder.encode(config, mpe.getContentType(), mpe.getContent());
entityBuilder.addBinaryBody(mpe.getFieldName(), encodedBytes, parse(mpe.getContentType()), mpe.getFileName());
}
}
request.setContentType(boundaryContentType);
ts.toServer(entityBuilder.build().getContent());
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public static HttpEntity getMultiPartEntity(String fileName, String contentType, InputStream fileStream, Map<String, String> additionalFormFields) throws IOException {
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
if (additionalFormFields != null && !additionalFormFields.isEmpty()) {
for (Entry<String, String> field : additionalFormFields.entrySet()) {
entityBuilder.addTextBody(field.getKey(), field.getValue());
}
}
entityBuilder.addBinaryBody(fileName, IOUtils.toByteArray(fileStream), ContentType.create(contentType), fileName);
return entityBuilder.build();
}
@Override
public final Message execute(SendPhoto sendPhoto) throws TelegramApiException {
assertParamNotNull(sendPhoto, "sendPhoto");
sendPhoto.validate();
try {
String url = getBaseUrl() + SendPhoto.PATH;
HttpPost httppost = configuredHttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setLaxMode();
builder.setCharset(StandardCharsets.UTF_8);
builder.addTextBody(SendPhoto.CHATID_FIELD, sendPhoto.getChatId(), TEXT_PLAIN_CONTENT_TYPE);
addInputFile(builder, sendPhoto.getPhoto(), SendPhoto.PHOTO_FIELD, true);
if (sendPhoto.getReplyMarkup() != null) {
builder.addTextBody(SendPhoto.REPLYMARKUP_FIELD, objectMapper.writeValueAsString(sendPhoto.getReplyMarkup()), TEXT_PLAIN_CONTENT_TYPE);
}
if (sendPhoto.getReplyToMessageId() != null) {
builder.addTextBody(SendPhoto.REPLYTOMESSAGEID_FIELD, sendPhoto.getReplyToMessageId().toString(), TEXT_PLAIN_CONTENT_TYPE);
}
if (sendPhoto.getCaption() != null) {
builder.addTextBody(SendPhoto.CAPTION_FIELD, sendPhoto.getCaption(), TEXT_PLAIN_CONTENT_TYPE);
if (sendPhoto.getParseMode() != null) {
builder.addTextBody(SendPhoto.PARSEMODE_FIELD, sendPhoto.getParseMode(), TEXT_PLAIN_CONTENT_TYPE);
}
}
if (sendPhoto.getDisableNotification() != null) {
builder.addTextBody(SendPhoto.DISABLENOTIFICATION_FIELD, sendPhoto.getDisableNotification().toString(), TEXT_PLAIN_CONTENT_TYPE);
}
HttpEntity multipart = builder.build();
httppost.setEntity(multipart);
return sendPhoto.deserializeResponse(sendHttpPostRequest(httppost));
} catch (IOException e) {
throw new TelegramApiException("Unable to send photo", e);
}
}
@Override
public Boolean execute(AddStickerToSet addStickerToSet) throws TelegramApiException {
assertParamNotNull(addStickerToSet, "addStickerToSet");
addStickerToSet.validate();
try {
String url = getBaseUrl() + AddStickerToSet.PATH;
HttpPost httppost = configuredHttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setLaxMode();
builder.setCharset(StandardCharsets.UTF_8);
builder.addTextBody(AddStickerToSet.USERID_FIELD, addStickerToSet.getUserId().toString(), TEXT_PLAIN_CONTENT_TYPE);
builder.addTextBody(AddStickerToSet.NAME_FIELD, addStickerToSet.getName(), TEXT_PLAIN_CONTENT_TYPE);
builder.addTextBody(AddStickerToSet.EMOJIS_FIELD, addStickerToSet.getEmojis(), TEXT_PLAIN_CONTENT_TYPE);
if (addStickerToSet.getPngSticker() != null) {
addInputFile(builder, addStickerToSet.getPngSticker(), AddStickerToSet.PNGSTICKER_FIELD, true);
} else {
addInputFile(builder, addStickerToSet.getTgsSticker(), AddStickerToSet.TGSSTICKER_FIELD, true);
}
if (addStickerToSet.getMaskPosition() != null) {
builder.addTextBody(AddStickerToSet.MASKPOSITION_FIELD, objectMapper.writeValueAsString(addStickerToSet.getMaskPosition()), TEXT_PLAIN_CONTENT_TYPE);
}
HttpEntity multipart = builder.build();
httppost.setEntity(multipart);
return addStickerToSet.deserializeResponse(sendHttpPostRequest(httppost));
} catch (IOException e) {
throw new TelegramApiException("Unable to add sticker to set", e);
}
}
public static HttpEntity createMultipartFormEntity(Map<String, String> parameters, InputStream is) {
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
multipartEntityBuilder.addBinaryBody("file", is, ContentType.create("application/octet-stream"), "file");
for (Entry<String, String> entry : parameters.entrySet()) {
if (entry.getValue() != null) {
multipartEntityBuilder.addTextBody(entry.getKey(), entry.getValue());
}
}
return multipartEntityBuilder.build();
}
private void addInputData(MultipartEntityBuilder builder, List<InputMedia> media, String mediaField) throws JsonProcessingException {
for (InputMedia inputMedia : media) {
addInputData(builder, inputMedia, null, false);
}
builder.addTextBody(mediaField, objectMapper.writeValueAsString(media), TEXT_PLAIN_CONTENT_TYPE);
}
private void addInputFile(MultipartEntityBuilder builder, InputFile file, String fileField, boolean addField) {
if (file.isNew()) {
if (file.getNewMediaFile() != null) {
builder.addBinaryBody(file.getMediaName(), file.getNewMediaFile(), ContentType.APPLICATION_OCTET_STREAM, file.getMediaName());
} else if (file.getNewMediaStream() != null) {
builder.addBinaryBody(file.getMediaName(), file.getNewMediaStream(), ContentType.APPLICATION_OCTET_STREAM, file.getMediaName());
}
}
if (addField) {
builder.addTextBody(fileField, file.getAttachName(), TEXT_PLAIN_CONTENT_TYPE);
}
}
/**
* Attach a local file to the a testcase in the Test Explorer DB.
* <br>The file must not be bigger than 10MB
*
* @param testcaseId the testcase id to which the file will be attached
* @param fileLocation the absolute path to the file
* @param testExplorerContextName the name of the web application, e.g. "TestExplorer" or "TestExplorer-4.0.0" etc.
* @param testExplorerPort the port of the web application, e.g. 8080
* @return TRUE if the operation was successful and false if not. A warning will be logged on failure.
*/
@PublicAtsApi
public boolean attachFileToTestcase( int testcaseId,
String fileLocation,
String testExplorerContextName,
int testExplorerPort ) {
fileLocation = fileLocation.replace("\\", "/");
currentErrMsgPrefix = ERR_MSG_PREFIX.replace("{FILE}", fileLocation).replace("{testcaseID}", testcaseId + "");
if (!checkFileExist(fileLocation)) {
return false;
}
if (!checkFileSizeIsNotTooLarge(fileLocation)) {
return false;
}
ActiveDbAppender dbAppender = ActiveDbAppender.getCurrentInstance();
if (dbAppender == null) {
logger.warn(currentErrMsgPrefix + ". Perhaps the database logging is turned off");
return false;
}
final int runId = dbAppender.getRunId();
final int suiteId = dbAppender.getSuiteId();
/* Since the user provides testcase ID, we have to validate it - whether it refers to a testcase part of
* the current run and suite
*/
if (runId < 1 || suiteId < 1 || testcaseId < 1) {
logger.warn(currentErrMsgPrefix + ". Perhaps the database logging is turned off or you are trying to "
+ "log while a testcase is not yet started");
return false;
}
final String database = dbAppender.getDatabase();
final String host = dbAppender.getHost();
final String URL = "http://" + host + ":" + testExplorerPort + "/" + testExplorerContextName
+ "/AttachmentsServlet";
URL url = null;
try {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(URL);
url = post.getURI().toURL();
if (!isURLConnetionAvailable(url)) {
return false;
}
logger.debug("POSTing " + fileLocation + " to " + URL);
File file = new File(fileLocation);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, fileLocation);
builder.addTextBody("dbName", database);
builder.addTextBody("runId", Integer.toString(runId));
builder.addTextBody("suiteId", Integer.toString(suiteId));
builder.addTextBody("testcaseId", Integer.toString(testcaseId));
HttpEntity entity = builder.build();
post.setEntity(entity);
return checkPostExecutedSuccessfully(client.execute(post), fileLocation, testcaseId);
} catch (FileNotFoundException fnfe) {
logger.warn(currentErrMsgPrefix + ". It does not exist on the local file system", fnfe);
return false;
} catch (IOException ioe) {
logger.warn(currentErrMsgPrefix + ". Upload to \"" + url + "\" failed", ioe);
return false;
}
}
@Test
public void testGenerateSignedPostPolicyV4() throws Exception {
PrintStream systemOut = System.out;
final ByteArrayOutputStream snippetOutputCapture = new ByteArrayOutputStream();
System.setOut(new PrintStream(snippetOutputCapture));
GenerateSignedPostPolicyV4.generateSignedPostPolicyV4(PROJECT_ID, BUCKET, "my-object");
String snippetOutput = snippetOutputCapture.toString();
System.setOut(systemOut);
assertTrue(
snippetOutput.contains("<form action='https://storage.googleapis.com/" + BUCKET + "/'"));
assertTrue(snippetOutput.contains("<input name='key' value='my-object'"));
assertTrue(snippetOutput.contains("<input name='x-goog-signature'"));
assertTrue(snippetOutput.contains("<input name='x-goog-date'"));
assertTrue(snippetOutput.contains("<input name='x-goog-credential'"));
assertTrue(snippetOutput.contains("<input name='x-goog-algorithm' value='GOOG4-RSA-SHA256'"));
assertTrue(snippetOutput.contains("<input name='policy'"));
assertTrue(snippetOutput.contains("<input name='x-goog-meta-test' value='data'"));
assertTrue(snippetOutput.contains("<input type='file' name='file'/>"));
String[] output = snippetOutput.split("'");
HttpClient client = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(output[1]);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
Map<String, String> policy = new HashMap<>();
/**
* When splitting by "'", any element in the form has its value two array elements ahead of it,
* for example ["x-goog-algorithm", "value=", "GOOG4-RSA-SHA256"] We take advantage of this to
* make a map which has any policy element easily accessible. The map also has a lot of noise,
* but we just use the parts we need
*/
for (int i = 3; i < output.length - 3; i += 2) {
policy.put(output[i], output[i + 2]);
}
builder.addTextBody("x-goog-date", policy.get("x-goog-date"));
builder.addTextBody("x-goog-meta-test", "data");
builder.addTextBody("x-goog-algorithm", "GOOG4-RSA-SHA256");
builder.addTextBody("x-goog-credential", policy.get("x-goog-credential"));
builder.addTextBody("key", "my-object");
builder.addTextBody("x-goog-signature", policy.get("x-goog-signature"));
builder.addTextBody("policy", policy.get("policy"));
File file = File.createTempFile("temp", "file");
Files.write(file.toPath(), "hello world".getBytes());
builder.addBinaryBody(
"file", new FileInputStream(file), ContentType.APPLICATION_OCTET_STREAM, file.getName());
request.setEntity(builder.build());
client.execute(request);
assertEquals("hello world", new String(storage.get(BUCKET, "my-object").getContent()));
}
public static String uploadFile(String url, File file) throws ClientProtocolException, IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpResponse httpResponse = null;
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
// multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
// File file = new File("F:\\Ken\\1.PNG");
// FileBody bin = new FileBody(file);
// multipartEntityBuilder.addBinaryBody("file", file,ContentType.create("image/png"),"abc.pdf");
// 当设置了setSocketTimeout参数后,以下代码上传PDF不能成功,将setSocketTimeout参数去掉后此可以上传成功。上传图片则没有个限制
// multipartEntityBuilder.addBinaryBody("file",file,ContentType.create("application/octet-stream"),"abd.pdf");
multipartEntityBuilder.addBinaryBody("file", file);
// multipartEntityBuilder.addPart("comment", new StringBody("This is comment", ContentType.TEXT_PLAIN));
multipartEntityBuilder.addTextBody("comment", "this is comment");
HttpEntity httpEntity = multipartEntityBuilder.build();
httpPost.setEntity(httpEntity);
httpResponse = httpClient.execute(httpPost);
HttpEntity responseEntity = httpResponse.getEntity();
int statusCode = httpResponse.getStatusLine().getStatusCode();
StringBuffer buffer = new StringBuffer();
if (statusCode == 200) {
BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
String str = "";
while (StringUtils.isNotEmpty(str = reader.readLine())) {
buffer.append(str);
}
}
httpClient.close();
if (httpResponse != null) {
httpResponse.close();
}
System.out.println("响应数据:" + buffer.toString());
return buffer.toString();
}