List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder build
public HttpEntity build()
From source file:functionaltests.RestSchedulerJobTaskTest.java
@Test public void testLoginWithCredentials() throws Exception { RestFuncTestConfig config = RestFuncTestConfig.getInstance(); Credentials credentials = RestFuncTUtils.createCredentials(config.getLogin(), config.getPassword(), RestFuncTHelper.getSchedulerPublicKey()); String schedulerUrl = getResourceUrl("login"); HttpPost httpPost = new HttpPost(schedulerUrl); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().addPart("credential", new ByteArrayBody(credentials.getBase64(), ContentType.APPLICATION_OCTET_STREAM, null)); httpPost.setEntity(multipartEntityBuilder.build()); HttpResponse response = executeUriRequest(httpPost); assertHttpStatusOK(response);/*from w w w . j av a 2 s . c o m*/ String sessionId = assertContentNotEmpty(response); String currentUserUrl = getResourceUrl("logins/sessionid/" + sessionId); HttpGet httpGet = new HttpGet(currentUserUrl); response = executeUriRequest(httpGet); assertHttpStatusOK(response); String userName = assertContentNotEmpty(response); Assert.assertEquals(config.getLogin(), userName); }
From source file:com.frochr123.periodictasks.RefreshProjectorThread.java
public void updateProjectorImage() { if (!updateInProgress && !shutdownThreadRunning) { updateInProgress = true;// w w w . java 2s . com new Thread() { @Override public void run() { try { if (VisicutModel.getInstance() != null && VisicutModel.getInstance().getSelectedLaserDevice() != null && VisicutModel.getInstance().getSelectedLaserDevice().getProjectorURL() != null && !VisicutModel.getInstance().getSelectedLaserDevice().getProjectorURL() .isEmpty()) { BufferedImage img = PreviewImageExport.generateImage(getProjectorWidth(), getProjectorHeight(), !isShutdownInProgress()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PreviewImageExport.writePngToOutputStream(outputStream, img); byte[] imagePostDataByte = outputStream.toByteArray(); // Create HTTP client and cusomized config for timeouts CloseableHttpClient httpClient = HttpClients.createDefault(); RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(DEFAULT_PROJECTOR_TIMEOUT) .setConnectTimeout(DEFAULT_PROJECTOR_TIMEOUT) .setConnectionRequestTimeout(DEFAULT_PROJECTOR_TIMEOUT).build(); // Create HTTP Post request HttpPost httpPost = new HttpPost( VisicutModel.getInstance().getSelectedLaserDevice().getProjectorURL()); httpPost.setConfig(requestConfig); // Insert file upload MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addBinaryBody("data", imagePostDataByte, ContentType.APPLICATION_OCTET_STREAM, "data"); HttpEntity httpEntity = multipartEntityBuilder.build(); httpPost.setEntity(httpEntity); // Set authentication information String encodedCredentials = Helper.getEncodedCredentials( VisicutModel.getInstance().getSelectedLaserDevice().getURLUser(), VisicutModel.getInstance().getSelectedLaserDevice().getURLPassword()); if (!encodedCredentials.isEmpty()) { httpPost.addHeader("Authorization", "Basic " + encodedCredentials); } // Send request CloseableHttpResponse res = httpClient.execute(httpPost); // React to possible server side errors if (res.getStatusLine() == null || res.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new Exception("Server sent wrong HTTP status code: " + new Integer(res.getStatusLine().getStatusCode()).toString()); } // Close everything correctly res.close(); httpClient.close(); } } // This is caused internally in apache commons library for wrong authentication // Would need to add additional apache commons library file to get a correct exception back for that catch (NoClassDefFoundError error) { // Set flag for exception handling, sleep and message lastExceptionMessage = "Projector thread exception: Authentication error!"; } catch (Exception e) { // Set flag for exception handling, sleep and message lastExceptionMessage = "Projector thread exception (2): " + e.getMessage(); } updateInProgress = false; // Need to check if shutdown is set here first, otherwise these asynchronous calls // would always overwrite a call to shutdown in progress = true if (shutdownInProgress) { shutdownInProgress = false; } } }.start(); } }
From source file:org.jboss.as.test.integration.management.http.HttpGenericOperationUnitTestCase.java
/** * Execute the post request.//from w ww . jav a2 s . c o m * * @param operation the operation body * @param encoded whether it should send the dmr encoded header * @param streams the optional input streams * @return the response from the server * @throws IOException */ private ModelNode executePost(final ContentBody operation, final boolean encoded, final List<ContentBody> streams) throws IOException { final HttpPost post = new HttpPost(uri); post.setHeader("X-Management-Client-Name", "test-client"); final MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().addPart("operation", operation); for (ContentBody stream : streams) { entityBuilder.addPart("input-streams", stream); } post.setEntity(entityBuilder.build()); return parseResponse(httpClient.execute(post), encoded); }
From source file:org.mule.module.http.functional.listener.HttpListenerAttachmentsTestCase.java
private HttpEntity getMultipartEntity(boolean withFile) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody(TEXT_BODY_FIELD_NAME, TEXT_BODY_FIELD_VALUE, ContentType.TEXT_PLAIN); if (withFile) { builder.addBinaryBody(FILE_BODY_FIELD_NAME, FILE_BODY_FIELD_VALUE.getBytes(), ContentType.APPLICATION_OCTET_STREAM, FIELD_BDOY_FILE_NAME); }//w ww.j a v a 2 s . co m return builder.build(); }
From source file:com.smartling.api.sdk.FileApiClientAdapterImpl.java
private HttpPost createFileUploadHttpPostRequest(final String apiParameters, final ContentBody contentBody) { final MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create() .addPart(FileApiParams.FILE, contentBody); final HttpPost httpPost = new HttpPost(String.format(UPLOAD_FILE_API_URL, baseApiUrl) + apiParameters); httpPost.setEntity(multipartEntityBuilder.build()); return httpPost; }
From source file:me.vertretungsplan.parser.LoginHandler.java
private String handleLogin(Executor executor, CookieStore cookieStore, boolean needsResponse) throws JSONException, IOException, CredentialInvalidException { if (auth == null) return null; if (!(auth instanceof UserPasswordCredential || auth instanceof PasswordCredential)) { throw new IllegalArgumentException("Wrong authentication type"); }/*from w ww. j a v a2 s . c o m*/ String login; String password; if (auth instanceof UserPasswordCredential) { login = ((UserPasswordCredential) auth).getUsername(); password = ((UserPasswordCredential) auth).getPassword(); } else { login = null; password = ((PasswordCredential) auth).getPassword(); } JSONObject data = scheduleData.getData(); JSONObject loginConfig = data.getJSONObject(LOGIN_CONFIG); String type = loginConfig.optString(PARAM_TYPE, "post"); switch (type) { case "post": List<Cookie> cookieList = cookieProvider != null ? cookieProvider.getCookies(auth) : null; if (cookieList != null && !needsResponse) { for (Cookie cookie : cookieList) cookieStore.addCookie(cookie); String checkUrl = loginConfig.optString(PARAM_CHECK_URL, null); String checkText = loginConfig.optString(PARAM_CHECK_TEXT, null); if (checkUrl != null && checkText != null) { String response = executor.execute(Request.Get(checkUrl)).returnContent().asString(); if (!response.contains(checkText)) { return null; } } else { return null; } } executor.clearCookies(); Document preDoc = null; if (loginConfig.has(PARAM_PRE_URL)) { String preUrl = loginConfig.getString(PARAM_PRE_URL); String preHtml = executor.execute(Request.Get(preUrl)).returnContent().asString(); preDoc = Jsoup.parse(preHtml); } String postUrl = loginConfig.getString(PARAM_URL); JSONObject loginData = loginConfig.getJSONObject(PARAM_DATA); List<NameValuePair> nvps = new ArrayList<>(); String typo3Challenge = null; if (loginData.has("_hiddeninputs") && preDoc != null) { for (Element hidden : preDoc.select(loginData.getString("_hiddeninputs") + " input[type=hidden]")) { nvps.add(new BasicNameValuePair(hidden.attr("name"), hidden.attr("value"))); if (hidden.attr("name").equals("challenge")) { typo3Challenge = hidden.attr("value"); } } } for (String name : JSONObject.getNames(loginData)) { String value = loginData.getString(name); if (name.equals("_hiddeninputs")) continue; switch (value) { case "_login": value = login; break; case "_password": value = password; break; case "_password_md5": value = DigestUtils.md5Hex(password); break; case "_password_md5_typo3": value = DigestUtils.md5Hex(login + ":" + DigestUtils.md5Hex(password) + ":" + typo3Challenge); break; } nvps.add(new BasicNameValuePair(name, value)); } Request request = Request.Post(postUrl); if (loginConfig.optBoolean("form-data", false)) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (NameValuePair nvp : nvps) { builder.addTextBody(nvp.getName(), nvp.getValue()); } request.body(builder.build()); } else { request.bodyForm(nvps, Charset.forName("UTF-8")); } String html = executor.execute(request).returnContent().asString(); if (cookieProvider != null) cookieProvider.saveCookies(auth, cookieStore.getCookies()); String checkUrl = loginConfig.optString(PARAM_CHECK_URL, null); String checkText = loginConfig.optString(PARAM_CHECK_TEXT, null); if (checkUrl != null && checkText != null) { String response = executor.execute(Request.Get(checkUrl)).returnContent().asString(); if (response.contains(checkText)) throw new CredentialInvalidException(); } else if (checkText != null) { if (html.contains(checkText)) throw new CredentialInvalidException(); } return html; case "basic": if (login == null) throw new IOException("wrong auth type"); executor.auth(login, password); if (loginConfig.has(PARAM_URL)) { String url = loginConfig.getString(PARAM_URL); if (executor.execute(Request.Get(url)).returnResponse().getStatusLine().getStatusCode() != 200) { throw new CredentialInvalidException(); } } break; case "ntlm": if (login == null) throw new IOException("wrong auth type"); executor.auth(login, password, null, null); if (loginConfig.has(PARAM_URL)) { String url = loginConfig.getString(PARAM_URL); if (executor.execute(Request.Get(url)).returnResponse().getStatusLine().getStatusCode() != 200) { throw new CredentialInvalidException(); } } break; case "fixed": String loginFixed = loginConfig.optString(PARAM_LOGIN, null); String passwordFixed = loginConfig.getString(PARAM_PASSWORD); if (!Objects.equals(loginFixed, login) || !Objects.equals(passwordFixed, password)) { throw new CredentialInvalidException(); } break; } return null; }
From source file:org.biouno.figshare.FigShareClient.java
/** * Upload a file to an article.// www . java2 s. c o m * * @param articleId article ID * @param file java.io.File file * @return org.biouno.figshare.v1.model.File uploaded file, without the thumbnail URL */ public org.biouno.figshare.v1.model.File uploadFile(long articleId, File file) { HttpClient httpClient = null; try { final String method = String.format("my_data/articles/%d/files", articleId); // create an HTTP request to a protected resource final String url = getURL(endpoint, version, method); // create an HTTP request to a protected resource final HttpPut request = new HttpPut(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); ContentBody body = new FileBody(file); FormBodyPart part = FormBodyPartBuilder.create("filedata", body).build(); builder.addPart(part); HttpEntity entity = builder.build(); request.setEntity(entity); // sign the request consumer.sign(request); // send the request httpClient = HttpClientBuilder.create().build(); HttpResponse response = httpClient.execute(request); HttpEntity responseEntity = response.getEntity(); String json = EntityUtils.toString(responseEntity); org.biouno.figshare.v1.model.File uploadedFile = readFileFromJson(json); return uploadedFile; } catch (OAuthCommunicationException e) { throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e); } catch (OAuthMessageSignerException e) { throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e); } catch (OAuthExpectationFailedException e) { throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e); } catch (ClientProtocolException e) { throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e); } catch (IOException e) { throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e); } }
From source file:com.alibaba.shared.django.DjangoClient.java
public DjangoMessage uploadFile(final byte[] bytes, final String filename) throws IOException, URISyntaxException { return executeRequest(new Supplier<HttpUriRequest>() { public HttpUriRequest get() { HttpPost post = new HttpPost(uploadFileUrl); MultipartEntityBuilder meb = MultipartEntityBuilder.create(); meb.addTextBody(ACCESS_TOKEN_KEY, accessToken()).addTextBody("md5", Digests.md5(bytes)) .addBinaryBody(FILE_KEY, bytes, ContentType.APPLICATION_XML, filename); post.setEntity(meb.build()); return post; }/*from w ww . ja va 2 s .c o m*/ }); }
From source file:io.swagger.client.api.DefaultApi.java
/** * Channel sync availability//from w w w . j a v a 2 s .c o m * Checks if a list of client channel identifiers are currently broadcasting synchronizable content * @param authorization Authorization token ('Bearer <token>') * @param channelIdList List of client channel IDs as a comma separated list * @param acceptLanguage Client locale, as <language>-<country> * @param contentType application/json * @return List<ChannelStatus> */ public List<ChannelStatus> getReadyChannels(String authorization, List<String> channelIdList, String acceptLanguage, String contentType) throws ApiException { Object localVarPostBody = null; // verify the required parameter 'authorization' is set if (authorization == null) { throw new ApiException(400, "Missing the required parameter 'authorization' when calling getReadyChannels"); } // verify the required parameter 'channelIdList' is set if (channelIdList == null) { throw new ApiException(400, "Missing the required parameter 'channelIdList' when calling getReadyChannels"); } // create path and map variables String localVarPath = "/channels/{channel_id_list}/ready".replaceAll("\\{format\\}", "json") .replaceAll("\\{" + "channel_id_list" + "\\}", apiInvoker.escapeString(channelIdList.toString())); // query params List<Pair> localVarQueryParams = new ArrayList<Pair>(); // header params Map<String, String> localVarHeaderParams = new HashMap<String, String>(); // form params Map<String, String> localVarFormParams = new HashMap<String, String>(); localVarHeaderParams.put("Authorization", ApiInvoker.parameterToString(authorization)); localVarHeaderParams.put("Accept-Language", ApiInvoker.parameterToString(acceptLanguage)); localVarHeaderParams.put("Content-Type", ApiInvoker.parameterToString(contentType)); String[] localVarContentTypes = { "application/json" }; String localVarContentType = localVarContentTypes.length > 0 ? localVarContentTypes[0] : "application/json"; if (localVarContentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); localVarPostBody = localVarBuilder.build(); } else { // normal form params } try { String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType); if (localVarResponse != null) { return (List<ChannelStatus>) ApiInvoker.deserialize(localVarResponse, "array", ChannelStatus.class); } else { return null; } } catch (ApiException ex) { throw ex; } }