List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder create
public static MultipartEntityBuilder create()
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"); }//w w w. j av a 2s.com 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:de.tu_dortmund.ub.data.dswarm.Ingest.java
/** * upload a file and update an existing resource with it * * @param resourceUUID//from w w w.ja v a 2 s .c om * @param filename * @param name * @param description * @return responseJson * @throws Exception */ private String uploadFileAndUpdateResource(final String resourceUUID, final String filename, final String name, final String description, final String serviceName, final String engineDswarmAPI) throws Exception { if (null == resourceUUID) throw new Exception("ID of the resource to update was null."); final String resourceWatchFolder = config.getProperty(TPUStatics.RESOURCE_WATCHFOLDER_IDENTIFIER); final String completeFileName = resourceWatchFolder + File.separatorChar + filename; try (final CloseableHttpClient httpclient = HttpClients.createDefault()) { final HttpPut httpPut = new HttpPut( engineDswarmAPI + DswarmBackendStatics.RESOURCES_ENDPOINT + APIStatics.SLASH + resourceUUID); final File file1 = new File(completeFileName); final FileBody fileBody = new FileBody(file1); final StringBody stringBodyForName = new StringBody(name, ContentType.TEXT_PLAIN); final StringBody stringBodyForDescription = new StringBody(description, ContentType.TEXT_PLAIN); final HttpEntity reqEntity = MultipartEntityBuilder.create() .addPart(DswarmBackendStatics.NAME_IDENTIFIER, stringBodyForName) .addPart(DswarmBackendStatics.DESCRIPTION_IDENTIFIER, stringBodyForDescription) .addPart(FILE_IDENTIFIER, fileBody).build(); httpPut.setEntity(reqEntity); LOG.info(String.format("[%s] request : %s", serviceName, httpPut.getRequestLine())); try (final CloseableHttpResponse httpResponse = httpclient.execute(httpPut)) { final int statusCode = httpResponse.getStatusLine().getStatusCode(); final String message = String.format("[%s] %d : %s", serviceName, statusCode, httpResponse.getStatusLine().getReasonPhrase()); final String response = TPUUtil.getResponseMessage(httpResponse); switch (statusCode) { case 200: { LOG.info(message); LOG.debug(String.format("[%s] responseJson : %s", serviceName, response)); return response; } default: { LOG.error(message); throw new Exception("something went wrong at data model export: " + message + " " + response); } } } } }
From source file:com.nridge.ds.solr.SolrConfigSet.java
/** * Uploads the Solr config set ZIP file into the search cluster. * * @see <a href="http://lucene.apache.org/solr/guide/7_6/configsets-api.html">Solr ConfigSets API</a> * @see <a href="https://www.baeldung.com/httpclient-post-http-request">Upload Binary File with HttpClient 4</a> * * @param aPathFileName Path file name of ZIP containing the configuration set. * @param aConfigSetName Config set name. * * @throws DSException Solr Data Source exception. *///from w w w .j a v a2 s .c om public void uploadZipFile(String aPathFileName, String aConfigSetName) throws DSException { Logger appLogger = mAppMgr.getLogger(this, "uploadZipFile"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); initialize(); String baseSolrURL = mSolrDS.getBaseURL(false); String solrURI = String.format("%s/admin/configs?action=UPLOAD&name=%s", baseSolrURL, aConfigSetName); File pathFile = new File(aPathFileName); CloseableHttpResponse httpResponse = null; HttpPost httpPost = new HttpPost(solrURI); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addBinaryBody("file", pathFile, ContentType.APPLICATION_OCTET_STREAM, "file.zip"); HttpEntity httpEntity = multipartEntityBuilder.build(); httpPost.setEntity(httpEntity); CloseableHttpClient httpClient = HttpClients.createDefault(); try { httpResponse = httpClient.execute(httpPost); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); String msgStr = String.format("%s [%d]: %s", solrURI, statusCode, statusLine); appLogger.debug(msgStr); if (statusCode == HttpStatus.SC_OK) { httpEntity = httpResponse.getEntity(); EntityUtils.consume(httpEntity); } else { msgStr = String.format("%s [%d]: %s", solrURI, statusCode, statusLine); appLogger.error(msgStr); throw new DSException(msgStr); } } catch (IOException e) { String msgStr = String.format("%s: %s", solrURI, e.getMessage()); appLogger.error(msgStr, e); throw new DSException(msgStr); } finally { if (httpResponse != null) IO.closeQuietly(httpResponse); } appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); }
From source file:com.sugarcrm.candybean.webservices.WS.java
/** * 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 *//*from ww w .j a va2 s . c o m*/ 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); } } }
From source file:org.ops4j.pax.web.itest.base.HttpTestClient.java
public void testPostMultipart(String path, Map<String, Object> multipartContent, String expectedContent, int httpRC) throws IOException { HttpPost httppost = new HttpPost(path); httppost.addHeader("Accept-Language", "en-us;q=0.8,en;q=0.5"); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); for (Entry<String, Object> content : multipartContent.entrySet()) { if (content.getValue() instanceof String) { multipartEntityBuilder.addPart(content.getKey(), new StringBody((String) content.getValue(), ContentType.TEXT_PLAIN)); }/* w ww . j av a 2s . c o m*/ } httppost.setEntity(multipartEntityBuilder.build()); CloseableHttpResponse response = httpclient.execute(httppost, context); assertEquals("HttpResponseCode", httpRC, response.getStatusLine().getStatusCode()); String responseBodyAsString = EntityUtils.toString(response.getEntity()); if (expectedContent != null) { assertTrue("Content: " + responseBodyAsString, responseBodyAsString.contains(expectedContent)); } response.close(); }
From source file:net.ymate.platform.module.wechat.support.HttpClientHelper.java
public String doUpload(String url, File uploadFile) throws Exception { CloseableHttpClient _httpClient = __doBuildHttpClient(); try {//from w ww .ja va 2 s . c o m _LOG.debug("Upload File [" + uploadFile + "]"); String _result = EntityUtils .toString(_httpClient .execute(RequestBuilder.post().setUri(url) .setEntity(MultipartEntityBuilder.create() .addPart("media", new FileBody(uploadFile)).build()) .build()) .getEntity(), DEFAULT_CHARSET); _LOG.debug("Upload File [" + uploadFile + "] Response [" + _result + "]"); return _result; } finally { _httpClient.close(); } }
From source file:com.gargoylesoftware.htmlunit.HttpWebConnectionTest.java
/** * Test that the right file part is built for a file that doesn't exist. * @throws Exception if the test fails/*from w w w . j a va2 s.c o m*/ */ @Test public void buildFilePart() throws Exception { final String encoding = "ISO8859-1"; final KeyDataPair pair = new KeyDataPair("myFile", new File("this/doesnt_exist.txt"), "text/plain", encoding); final MultipartEntityBuilder builder = MultipartEntityBuilder.create().setLaxMode(); try (final HttpWebConnection webConnection = new HttpWebConnection(getWebClient())) { webConnection.buildFilePart(pair, builder); } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); builder.build().writeTo(baos); final String part = baos.toString(encoding); final String expected = "--(.*)\r\n" + "Content-Disposition: form-data; name=\"myFile\"; filename=\"doesnt_exist.txt\"\r\n" + "Content-Type: text/plain\r\n" + "\r\n" + "\r\n" + "--\\1--\r\n"; assertTrue(part, part.matches(expected)); }
From source file:mesquite.zephyr.RAxMLRunnerCIPRes.RAxMLRunnerCIPRes.java
public Object getProgramArguments(String dataFileName, boolean isPreflight) { MultipartEntityBuilder arguments = MultipartEntityBuilder.create(); StringBuffer sb = new StringBuffer(); if (!isPreflight) { getArguments(arguments, sb, dataFileName, proteinModel, dnaModel, otherOptions, bootstrapreps, bootstrapSeed, numRuns, outgroupTaxSetString, multipleModelFileName, false); logln("RAxML arguments: \n" + sb.toString() + "\n"); } else {//from ww w .j av a 2s . co m getArguments(arguments, sb, dataFileName, proteinModel, dnaModel, otherOptions, bootstrapreps, bootstrapSeed, numRuns, outgroupTaxSetString, multipleModelFileName, true); } return arguments; }
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); }//from w w w . ja v a 2 s . com return builder.build(); }
From source file:org.sahli.asciidoc.confluence.publisher.client.http.HttpRequestFactory.java
private static HttpEntity multipartEntity(String attachmentFileName, InputStream attachmentContent) { MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntityBuilder.setCharset(Charset.forName("UTF-8")); InputStreamBody inputStreamBody;/*from ww w .j ava2 s . co m*/ if (isNotBlank(attachmentFileName)) { inputStreamBody = new InputStreamBody(attachmentContent, APPLICATION_OCTET_STREAM, attachmentFileName); } else { inputStreamBody = new InputStreamBody(attachmentContent, APPLICATION_OCTET_STREAM); } multipartEntityBuilder.addPart("file", inputStreamBody); return multipartEntityBuilder.build(); }