org.apache.http.entity.mime.MultipartEntityBuilder Java Examples
The following examples show how to use
org.apache.http.entity.mime.MultipartEntityBuilder.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpFluentService.java From AthenaServing with Apache License 2.0 | 7 votes |
/** * 构建POST方法请求参数 * @return */ private HttpEntity buildPostParam(List<NameValuePair> nameValuePairs, List<File> files) { if(CollectionUtils.isEmpty(nameValuePairs) && CollectionUtils.isEmpty(files)) { return null; } if(!CollectionUtils.isEmpty(files)) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (File file : files) { builder.addBinaryBody(file.getName(), file, ContentType.APPLICATION_OCTET_STREAM, file.getName()); } for (NameValuePair nameValuePair : nameValuePairs) { //设置ContentType为UTF-8,默认为text/plain; charset=ISO-8859-1,传递中文参数会乱码 builder.addTextBody(nameValuePair.getName(), nameValuePair.getValue(), ContentType.create("text/plain", Consts.UTF_8)); } return builder.build(); } else { try { return new UrlEncodedFormEntity(nameValuePairs); } catch (UnsupportedEncodingException e) { LOGGER.error(e.getMessage(), e.toString()); } } return null; }
Example #2
Source File: HttpClientPool.java From message_interface with MIT License | 7 votes |
public String uploadFile(String url, String path) throws IOException { HttpPost post = new HttpPost(url); try { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody fileBody = new FileBody(new File(path)); //image should be a String builder.addPart("file", fileBody); post.setEntity(builder.build()); CloseableHttpResponse response = client.execute(post); return readResponse(response); } finally { post.releaseConnection(); } }
Example #3
Source File: RemoteTransformerClient.java From alfresco-repository with GNU Lesser General Public License v3.0 | 6 votes |
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(); }
Example #4
Source File: SampleClient.java From msf4j with Apache License 2.0 | 6 votes |
private static HttpEntity createMessageForComplexForm() { HttpEntity reqEntity = null; try { StringBody companyText = new StringBody("{\"type\": \"Open Source\"}", ContentType.APPLICATION_JSON); StringBody personList = new StringBody( "[{\"name\":\"Richard Stallman\",\"age\":63}, {\"name\":\"Linus Torvalds\",\"age\":46}]", ContentType.APPLICATION_JSON); reqEntity = MultipartEntityBuilder.create().addTextBody("id", "1") .addPart("company", companyText) .addPart("people", personList).addBinaryBody("file", new File( Thread.currentThread().getContextClassLoader().getResource("sample.txt").toURI()), ContentType.DEFAULT_BINARY, "sample.txt") .build(); } catch (URISyntaxException e) { log.error("Error while getting the file from resource." + e.getMessage(), e); } return reqEntity; }
Example #5
Source File: HttpClientMultipartLiveTest.java From tutorials with MIT License | 6 votes |
@Test public final void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException { final String message = "This is a multipart post"; final byte[] bytes = "binary code".getBytes(); final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addBinaryBody("file", bytes, ContentType.DEFAULT_BINARY, TEXTFILENAME); builder.addTextBody("text", message, ContentType.TEXT_PLAIN); final HttpEntity entity = builder.build(); post.setEntity(entity); response = client.execute(post); final int statusCode = response.getStatusLine() .getStatusCode(); final String responseString = getContent(); final String contentTypeInHeader = getContentTypeHeader(); assertThat(statusCode, equalTo(HttpStatus.SC_OK)); // assertTrue(responseString.contains("Content-Type: multipart/form-data;")); assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); System.out.println(responseString); System.out.println("POST Content Type: " + contentTypeInHeader); }
Example #6
Source File: CrashReportTask.java From archivo with GNU General Public License v3.0 | 6 votes |
private void performUpload() { Path gzLog = compressLog(); try (CloseableHttpClient client = buildHttpClient()) { HttpPost post = new HttpPost(CRASH_REPORT_URL); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody logFile = new FileBody(gzLog.toFile(), ContentType.DEFAULT_BINARY); builder.addPart("log", logFile); StringBody uid = new StringBody(userId, ContentType.TEXT_PLAIN); builder.addPart("uid", uid); HttpEntity postEntity = builder.build(); post.setEntity(postEntity); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() != 200) { logger.debug("Error uploading crash report: {}", response.getStatusLine()); } } catch (IOException e) { logger.error("Error uploading crash report: {}", e.getLocalizedMessage()); } }
Example #7
Source File: ZdsHttp.java From zest-writer with GNU General Public License v3.0 | 6 votes |
public String importImage(File file) throws IOException { if(getGalleryId() != null) { String url = getImportImageUrl(); HttpGet get = new HttpGet(url); HttpResponse response = client.execute(get, context); this.cookies = response.getFirstHeader(Constant.SET_COOKIE_HEADER).getValue(); // load file in form FileBody cbFile = new FileBody(file); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("physical", cbFile); builder.addPart("title", new StringBody("Image importée via ZestWriter", Charset.forName("UTF-8"))); builder.addPart(Constant.CSRF_ZDS_KEY, new StringBody(getCookieValue(cookieStore, Constant.CSRF_COOKIE_KEY), ContentType.MULTIPART_FORM_DATA)); Pair<Integer, String> resultPost = sendPost(url, builder.build()); Document doc = Jsoup.parse(resultPost.getValue()); Elements endPoints = doc.select("input[name=avatar_url]"); if(!endPoints.isEmpty()) { return getBaseUrl() + endPoints.first().attr("value").trim(); } } return "http://"; }
Example #8
Source File: HttpClientDelegate.java From wechat-sdk with Apache License 2.0 | 6 votes |
/** * 构造HttpUriRequest请求. * * @param method 请求方法 * @param url 请求地址 * @param params 请求(key,value)数据 * @param data 请求体文本数据 * @param file 请求体二进制文件 */ private static HttpUriRequest buildRequest(String method, String url, Map<String, String> params, String data, File file) { RequestBuilder builder = RequestBuilder.create(method).setUri(url); if (params != null) { for (String key : params.keySet()) { builder.addParameter(new BasicNameValuePair(key, params.get(key))); } } if (data != null) { builder.setEntity(new StringEntity(data, Const.Charset.UTF_8)); } if (file != null) { MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().addBinaryBody("media", file); builder.setEntity(entityBuilder.build()); } return builder.build(); }
Example #9
Source File: TokenDemo.java From ais-sdk with Apache License 2.0 | 6 votes |
/** * 英文海关识别,使用Base64编码后的文件方式,使用Token认证方式访问服务 * @param token token认证串 * @param formFile 文件路径 * @throws IOException */ public static void requestOcrCustomsFormEnBase64(String token, String formFile) { // 1.构建英文海关单据识别服务所需要的参数 String url = "https://ais.cn-north-1.myhuaweicloud.com/v1.0/ocr/action/ocr_form"; Header[] headers = new Header[] {new BasicHeader("X-Auth-Token", token) }; try { MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody fileBody = new FileBody(new File(formFile), ContentType.create("image/jpeg", "utf-8")); multipartEntityBuilder.addPart("file", fileBody); // 2.传入英文海关单据识别服务对应的参数, 使用POST方法调用服务并解析输出识别结果 HttpResponse response = HttpClientUtils.post(url, headers, multipartEntityBuilder.build()); System.out.println(response); String content = IOUtils.toString(response.getEntity().getContent()); System.out.println(content); } catch (Exception e) { e.printStackTrace(); } }
Example #10
Source File: OTATest.java From blynk-server with GNU General Public License v3.0 | 6 votes |
@Test public void testAuthorizationFailed() throws Exception { HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + 123); post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString("123:123".getBytes())); String fileName = "test.bin"; InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName); ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("upfile", fileBody); HttpEntity entity = builder.build(); post.setEntity(entity); try (CloseableHttpResponse response = httpclient.execute(post)) { assertEquals(403, response.getStatusLine().getStatusCode()); String error = TestUtil.consumeText(response); assertNotNull(error); assertEquals("Authentication failed.", error); } }
Example #11
Source File: HttpUploader.java From incubator-heron with Apache License 2.0 | 6 votes |
private URI uploadPackageAndGetURI(final CloseableHttpClient httpclient) throws IOException, URISyntaxException { File file = new File(this.topologyPackageLocation); String uploaderUri = HttpUploaderContext.getHeronUploaderHttpUri(this.config); post = new HttpPost(uploaderUri); FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart(FILE, fileBody); HttpEntity entity = builder.build(); post.setEntity(entity); HttpResponse response = execute(httpclient); String responseString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8.name()); LOG.fine("Topology package download URI: " + responseString); return new URI(responseString); }
Example #12
Source File: LoolFileConverter.java From sakai with Educational Community License v2.0 | 6 votes |
public static byte[] convert(String baseUrl, InputStream sourceInputStream) throws IOException { int timeoutMillis = 5000; RequestConfig config = RequestConfig.custom() .setConnectTimeout(timeoutMillis) .setConnectionRequestTimeout(timeoutMillis) .setSocketTimeout(timeoutMillis * 1000).build(); CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build(); HttpPost httpPost = new HttpPost(baseUrl + "/lool/convert-to/pdf"); HttpEntity multipart = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .addBinaryBody("data", sourceInputStream, ContentType.MULTIPART_FORM_DATA, "anything") .build(); httpPost.setEntity(multipart); CloseableHttpResponse response = client.execute(httpPost); byte[] convertedFileBytes = EntityUtils.toByteArray(response.getEntity()); client.close(); return convertedFileBytes; }
Example #13
Source File: JAXRSMultipartTest.java From cxf with Apache License 2.0 | 6 votes |
@Test public void testMultipartRequestTooLargeManyParts() throws Exception { CloseableHttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost("http://localhost:" + PORT + "/bookstore/books/image"); String ct = "multipart/mixed"; post.setHeader("Content-Type", ct); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); HttpEntity entity = builder.addPart("image", new ByteArrayBody(new byte[1024 * 9], "testfile.png")) .addPart("image", new ByteArrayBody(new byte[1024 * 11], "testfile2.png")).build(); post.setEntity(entity); try { CloseableHttpResponse response = client.execute(post); assertEquals(413, response.getStatusLine().getStatusCode()); } finally { // Release current connection to the connection pool once you are done post.releaseConnection(); } }
Example #14
Source File: OTATest.java From blynk-server with GNU General Public License v3.0 | 6 votes |
@Test public void testOTAWrongToken() throws Exception { HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + 123); post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth)); String fileName = "test.bin"; InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName); ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("upfile", fileBody); HttpEntity entity = builder.build(); post.setEntity(entity); try (CloseableHttpResponse response = httpclient.execute(post)) { assertEquals(400, response.getStatusLine().getStatusCode()); String error = TestUtil.consumeText(response); assertNotNull(error); assertEquals("Invalid token.", error); } }
Example #15
Source File: HttpUtil.java From common-project with Apache License 2.0 | 6 votes |
public static String sendPostFile(String url, File file, Map<String, String> data) { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); 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")); multipartEntityBuilder.addBinaryBody("file", file); if (data != null) { data.forEach((k, v) -> { multipartEntityBuilder.addTextBody(k, v); }); } HttpEntity httpEntity = multipartEntityBuilder.build(); httpPost.setEntity(httpEntity); try { CloseableHttpResponse response = httpClient.execute(httpPost); return EntityUtils.toString(response.getEntity()); } catch (IOException e) { e.printStackTrace(); } return null; }
Example #16
Source File: UpdateAPIImage.java From apimanager-swagger-promote with Apache License 2.0 | 6 votes |
public void execute() throws AppException { if(!desiredState.getImage().isValid()) { LOG.info("No image configured, doing nothing."); return; } LOG.info("Updating API-Image from: " + desiredState.getImage().getFilename()); URI uri; HttpEntity entity; try { uri = new URIBuilder(cmd.getAPIManagerURL()).setPath(RestAPICall.API_VERSION+"/proxies/"+actualState.getId()+"/image").build(); entity = MultipartEntityBuilder.create() .addBinaryBody("file", ((DesiredAPI)this.desiredState).getImage().getInputStream(), ContentType.create("image/jpeg"), desiredState.getImage().getBaseFilename()) .build(); RestAPICall apiCall = new POSTRequest(entity, uri, this); apiCall.setContentType(null); apiCall.execute(); } catch (Exception e) { throw new AppException("Can't update API-Image.", ErrorCode.UNXPECTED_ERROR, e); } }
Example #17
Source File: RestSchedulerJobTaskTest.java From scheduling with GNU Affero General Public License v3.0 | 6 votes |
@Test public void testUrlMatrixParamsShouldReplaceJobVariables() throws Exception { File jobFile = new File(RestSchedulerJobTaskTest.class.getResource("config/job_matrix_params.xml").toURI()); String schedulerUrl = getResourceUrl("submit;var=matrix_param_val"); HttpPost httpPost = new HttpPost(schedulerUrl); setSessionHeader(httpPost); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create() .addPart("file", new FileBody(jobFile, ContentType.APPLICATION_XML)); httpPost.setEntity(multipartEntityBuilder.build()); HttpResponse response = executeUriRequest(httpPost); assertHttpStatusOK(response); JSONObject jsonObj = toJsonObject(response); final String jobId = jsonObj.get("id").toString(); assertNotNull(jobId); waitJobState(jobId, JobStatus.FINISHED, TimeUnit.MINUTES.toMillis(1)); }
Example #18
Source File: HttpClient.java From utils with Apache License 2.0 | 6 votes |
private HttpPost postForm(String url, Map<String, String> params, Map<String, File> files, String charset) { if (StringUtils.isBlank(charset)) { charset = "UTF-8"; } HttpPost httpPost = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); if (null != params) { Set<String> keySet = params.keySet(); for (String key : keySet) { builder.addTextBody(key, params.get(key), ContentType.create("text/plain", Charset.forName(charset))); } } if (CollectionUtils.isBlank(files)) { for (String filename : files.keySet()) { builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addBinaryBody(filename, files.get(filename), ContentType.DEFAULT_BINARY, filename); } } httpPost.setEntity(builder.build()); return httpPost; }
Example #19
Source File: BasicHttpClient.java From zerocode with Apache License 2.0 | 6 votes |
/** * This is the http request builder for file uploads, using Apache Http Client. In case you want to build * or prepare the requests differently, you can override this method. * * Note- * With file uploads you can send more headers too from the testcase to the server, except "Content-Type" because * this is reserved for "multipart/form-data" which the client sends to server during the file uploads. You can * also send more request-params and "boundary" from the test cases if needed. The boundary defaults to an unique * string of local-date-time-stamp if not provided in the request. * * You can override this method via @UseHttpClient(YourCustomHttpClient.class) * * @param httpUrl * @param methodName * @param reqBodyAsString * @return * @throws IOException */ public RequestBuilder createFileUploadRequestBuilder(String httpUrl, String methodName, String reqBodyAsString) throws IOException { Map<String, Object> fileFieldNameValueMap = getFileFieldNameValue(reqBodyAsString); List<String> fileFieldsList = (List<String>) fileFieldNameValueMap.get(FILES_FIELD); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); /* * Allow fileFieldsList to be null. * fileFieldsList can be null if multipart/form-data is sent without any files * Refer Issue #168 - Raised and fixed by santhoshTpixler */ if(fileFieldsList != null) { buildAllFilesToUpload(fileFieldsList, multipartEntityBuilder); } buildOtherRequestParams(fileFieldNameValueMap, multipartEntityBuilder); buildMultiPartBoundary(fileFieldNameValueMap, multipartEntityBuilder); return createUploadRequestBuilder(httpUrl, methodName, multipartEntityBuilder); }
Example #20
Source File: DefaultAbsSender.java From TelegramBots with MIT License | 6 votes |
@Override public Boolean execute(SetStickerSetThumb setStickerSetThumb) throws TelegramApiException { assertParamNotNull(setStickerSetThumb, "setStickerSetThumb"); setStickerSetThumb.validate(); try { String url = getBaseUrl() + AddStickerToSet.PATH; HttpPost httppost = configuredHttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setLaxMode(); builder.setCharset(StandardCharsets.UTF_8); builder.addTextBody(SetStickerSetThumb.USERID_FIELD, setStickerSetThumb.getUserId().toString(), TEXT_PLAIN_CONTENT_TYPE); builder.addTextBody(SetStickerSetThumb.NAME_FIELD, setStickerSetThumb.getName(), TEXT_PLAIN_CONTENT_TYPE); addInputFile(builder, setStickerSetThumb.getThumb(), SetStickerSetThumb.THUMB_FIELD, true); HttpEntity multipart = builder.build(); httppost.setEntity(multipart); return setStickerSetThumb.deserializeResponse(sendHttpPostRequest(httppost)); } catch (IOException e) { throw new TelegramApiException("Unable to add sticker to set", e); } }
Example #21
Source File: WS.java From candybean with GNU Affero General Public License v3.0 | 6 votes |
/** * Private helper method to abstract creating a POST/PUT request. * Side Effect: Adds the body to the request * * @param request A PUT or POST request * @param body Map of Key Value pairs * @param contentType The intended content type of the body */ protected static void addBodyToRequest(HttpEntityEnclosingRequestBase request, Map<String, Object> body, ContentType contentType) { if (body != null) { if (contentType == ContentType.MULTIPART_FORM_DATA) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (Map.Entry<String, Object> entry : body.entrySet()) { builder.addTextBody(entry.getKey(), (String) entry.getValue()); } request.setEntity(builder.build()); } else { JSONObject jsonBody = new JSONObject(body); StringEntity strBody = new StringEntity(jsonBody.toJSONString(), ContentType.APPLICATION_JSON); request.setEntity(strBody); } } }
Example #22
Source File: FileSession.java From timer with Apache License 2.0 | 5 votes |
public Session addParams(Map<String,String> map){ MultipartEntityBuilder multipartEntity= (MultipartEntityBuilder) this.getProviderService().provider(); for(String key:map.keySet()){ multipartEntity.addTextBody(key,map.get(key)); } return this; }
Example #23
Source File: Qbittorrent.java From BoxHelper with GNU General Public License v3.0 | 5 votes |
@Override public boolean addTorrent(String link, String name, String hash, Long size, float downloadLimit, float uploadLimit) throws IOException { System.out.println("\u001b[37;1m [Info] \u001b[36m qBittorrent:\u001b[0m Adding torrent " + link.substring(0, link.indexOf("passkey") - 1) + " ..."); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://127.0.0.1:" + getPort() + "/api/v2/torrents/add"); httpPost.addHeader("User-Agent", "BoxHelper"); httpPost.addHeader("Host", "127.0.0.1:" + getPort()); httpPost.addHeader("Cookie", "SID=" + this.sessionID); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addTextBody("urls", link); multipartEntityBuilder.addTextBody("dlLimit", (int)(downloadLimit * 1024 * 1024) + ""); multipartEntityBuilder.addTextBody("upLimit", (int)(uploadLimit * 1024 * 1024) + ""); httpPost.setEntity(multipartEntityBuilder.build()); httpClient.execute(httpPost); httpClient.close(); boolean added =recheck(hash, name, size, TorrentState.DOWNLOADING); if (added) { System.out.println("\u001b[37;1m [Info] \u001b[36m qBittorrent:\u001b[0m Successfully added torrent " + link.substring(0, link.indexOf("passkey") - 1) + " ."); acquireTorrents(TorrentState.DOWNLOADING); for (Object torrent:this.downloadingTorrents) { if (((QbittorrentTorrents) torrent).getName().contains(name) || ((QbittorrentTorrents) torrent).getName().contains(name.replaceAll("\\s", "\\."))) { hash = ((QbittorrentTorrents) torrent).getHash(); break; } } } else System.out.println("\u001b[33;1m [Warning]\u001b[36m qBittorrent:\u001b[0m Cannot add torrent " + link.substring(0, link.indexOf("passkey") - 1) + " . Retry later..."); return added; }
Example #24
Source File: FileUploadDownloadClient.java From incubator-pinot with Apache License 2.0 | 5 votes |
private static HttpUriRequest getUploadFileRequest(String method, URI uri, ContentBody contentBody, @Nullable List<Header> headers, @Nullable List<NameValuePair> parameters, int socketTimeoutMs) { // Build the Http entity HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .addPart(contentBody.getFilename(), contentBody).build(); // Build the request RequestBuilder requestBuilder = RequestBuilder.create(method).setVersion(HttpVersion.HTTP_1_1).setUri(uri).setEntity(entity); addHeadersAndParameters(requestBuilder, headers, parameters); setTimeout(requestBuilder, socketTimeoutMs); return requestBuilder.build(); }
Example #25
Source File: FormControllerTest.java From mangooio with Apache License 2.0 | 5 votes |
@Test public void testSingleFileUpload(@TempDir Path tempDir) throws IOException { // given String host = Application.getInstance(Config.class).getConnectorHttpHost(); int port = Application.getInstance(Config.class).getConnectorHttpPort(); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // when Path path = tempDir.resolve(UUID.randomUUID().toString()); InputStream attachment = Resources.getResource("attachment.txt").openStream(); Files.copy(attachment, path); multipartEntityBuilder.addPart("attachment", new FileBody(path.toFile())); HttpPost httpPost = new HttpPost("http://" + host + ":" + port + "/singlefile"); httpPost.setEntity(multipartEntityBuilder.build()); String response = null; HttpResponse httpResponse = httpClientBuilder.build().execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { response = EntityUtils.toString(httpEntity); } // then assertThat(httpResponse, not(nullValue())); assertThat(response, not(nullValue())); assertThat(httpResponse.getStatusLine().getStatusCode(), equalTo(StatusCodes.OK)); assertThat(response, equalTo("This is an attachment")); }
Example #26
Source File: RequestPartTypeTests.java From vividus with Apache License 2.0 | 5 votes |
@MethodSource("fileContentTypes") @ParameterizedTest void testAddFilePart(Optional<String> contentTypeAsString, ContentType contentType) throws IOException { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); String name = "fileKey"; String fileName = "requestBody.txt"; RequestPartType.FILE.addPart(builder, name, "/" + fileName, contentTypeAsString); assertHttpEntity(builder, buildExpectedEntity(name + "\"; filename=\"" + fileName, contentType, "binary", "{body}")); }
Example #27
Source File: DefaultCosHttpClient.java From cos-java-sdk-v4 with MIT License | 5 votes |
private void setMultiPartEntity(HttpPost httpPost, Map<String, String> params) throws Exception { ContentType utf8TextPlain = ContentType.create("text/plain", Consts.UTF_8); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); for (String paramKey : params.keySet()) { if (paramKey.equals(RequestBodyKey.FILE_CONTENT)) { entityBuilder.addBinaryBody(RequestBodyKey.FILE_CONTENT, params .get(RequestBodyKey.FILE_CONTENT).getBytes(Charset.forName("ISO-8859-1"))); } else { entityBuilder.addTextBody(paramKey, params.get(paramKey), utf8TextPlain); } } httpPost.setEntity(entityBuilder.build()); }
Example #28
Source File: AppDeploymentService.java From flowable-engine with Apache License 2.0 | 5 votes |
public JsonNode uploadDeployment(ServerConfig serverConfig, String name, InputStream inputStream) throws IOException { HttpPost post = new HttpPost(clientUtil.getServerUrl(serverConfig, "app-repository/deployments")); HttpEntity reqEntity = MultipartEntityBuilder.create() .addBinaryBody(name, IOUtils.toByteArray(inputStream), ContentType.APPLICATION_OCTET_STREAM, name) .build(); post.setEntity(reqEntity); return clientUtil.executeRequest(post, serverConfig, 201); }
Example #29
Source File: UploadFile.java From tutorial with MIT License | 5 votes |
public static void main(String[] argvs) throws Exception{ File f1 = new File("src/test/resources/1.jpg"); File f2 = new File("src/test/resources/2.jpg"); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpEntity data = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.RFC6532) .addBinaryBody("photo", f1, ContentType.DEFAULT_BINARY, f1.getName()) .addBinaryBody("photo", f2, ContentType.DEFAULT_BINARY, f2.getName()) .addTextBody("fileId", "110", ContentType.DEFAULT_BINARY) .build(); HttpUriRequest request = RequestBuilder .post("http://127.0.0.1:8080/tvseries/10/photos") .setEntity(data) .build(); ResponseHandler<String> responseHandler = new ResponseHandler<String>() { @Override public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); System.out.println(status); if (status == 200) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }; String responseBody = httpClient.execute(request, responseHandler); System.out.println(responseBody); } }
Example #30
Source File: FileUploadUtils.java From zerocode with Apache License 2.0 | 5 votes |
public static void buildOtherRequestParams(Map<String, Object> fileFieldNameValueMap, MultipartEntityBuilder multipartEntityBuilder) { for (Map.Entry<String, Object> entry : fileFieldNameValueMap.entrySet()) { if (entry.getKey().equals(FILES_FIELD) || entry.getKey().equals(BOUNDARY_FIELD)) { continue; } multipartEntityBuilder.addPart(entry.getKey(), new StringBody((String) entry.getValue(), TEXT_PLAIN)); } }