List of usage examples for org.apache.http.client.fluent Request Post
public static Request Post(final String uri)
From source file:org.kie.smoke.wb.util.RestUtil.java
public static <T> T postEntity(URL deploymentUrl, String relativeUrl, String mediaType, int status, String user, String password, double timeoutInSecs, Object entity, Class<T>... responseTypes) { String uriStr = createBaseUriString(deploymentUrl, relativeUrl); ResponseHandler<T> rh = createResponseHandler(mediaType, status, responseTypes); String entityStr = ((AbstractResponseHandler) rh).serialize(entity); HttpEntity bodyEntity = null;// w ww . ja va2 s. c o m try { bodyEntity = new StringEntity(entityStr); } catch (UnsupportedEncodingException uee) { logAndFail("Unable to encode serialized " + entity.getClass().getSimpleName() + " entity", uee); } // @formatter:off Request request = Request.Post(uriStr).body(bodyEntity) .addHeader(HttpHeaders.CONTENT_TYPE, mediaType.toString()) .addHeader(HttpHeaders.ACCEPT, mediaType.toString()) .addHeader(HttpHeaders.AUTHORIZATION, basicAuthenticationHeader(user, password)); // @formatter:on Response resp = null; long before = 0, after = 0; try { logOp("POST", entity, uriStr); before = System.currentTimeMillis(); resp = request.execute(); after = System.currentTimeMillis(); } catch (Exception e) { logAndFail("[GET] " + uriStr, e); } long duration = after - before; assertTrue("Timeout exceeded " + timeoutInSecs + " secs: " + ((double) duration / 1000d) + " secs", duration < timeoutInSecs * 1000); try { return resp.handleResponse(rh); } catch (Exception e) { logAndFail("Failed retrieving response from [GET] " + uriStr, e); } // never happens return null; }
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 ww w.j a v a 2 s . co 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:de.elomagic.carafile.client.CaraFileClient.java
/** * Uploads a file (Multi chunk upload)./*w ww . j a va 2s . c om*/ * <p/> * Multi chunk upload means that the file will be devived in one or more chunks and each chunk can be downloaded to a different peer. * * @param path Must be a file and not a directory. File will not be deleted * @param filename Name of the file. If null then name of the parameter path will be used * @return Returns the {@link MetaData} of the uploaded stream * @throws IOException Thrown when unable to call REST services * @throws java.security.GeneralSecurityException Thrown when unable to determine SHA-1 of the file * @see CaraFileClient#uploadFile(java.net.URI, java.io.InputStream, java.lang.String, long) */ public MetaData uploadFile(final Path path, final String filename) throws IOException, GeneralSecurityException { if (registryURI == null) { throw new IllegalArgumentException("Parameter 'registryURI' must not be null!"); } if (path == null) { throw new IllegalArgumentException("Parameter 'path' must not be null!"); } if (Files.notExists(path)) { throw new FileNotFoundException("File \"" + path + "\" doesn't exists!"); } if (Files.isDirectory(path)) { throw new IOException("Parameter 'path' is not a file!"); } String fn = filename == null ? path.getFileName().toString() : filename; MetaData md = CaraFileUtils.createMetaData(path, fn); md.setRegistryURI(registryURI); String json = JsonUtil.write(md); LOG.debug("Register " + md.getId() + " file at " + registryURI.toString()); URI uri = CaraFileUtils.buildURI(registryURI, "registry", "register"); HttpResponse response = executeRequest(Request.Post(uri).bodyString(json, ContentType.APPLICATION_JSON)) .returnResponse(); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new IOException("Unable to register file. " + response.getStatusLine().getReasonPhrase()); } Set<PeerData> peerDataSet = downloadPeerSet(); byte[] buffer = new byte[md.getChunkSize()]; try (InputStream in = Files.newInputStream(path, StandardOpenOption.READ); BufferedInputStream bis = new BufferedInputStream(in, md.getChunkSize())) { int bytesRead; int chunkIndex = 0; while ((bytesRead = bis.read(buffer)) > 0) { String chunkId = md.getChunk(chunkIndex).getId(); URI peerURI = peerSelector.getURI(peerDataSet, chunkIndex); URI seedChunkUri = CaraFileUtils.buildURI(peerURI, "peer", "seedChunk", chunkId); LOG.debug("Uploading chunk " + chunkId + " to peer " + seedChunkUri.toString() + ";Index=" + chunkIndex + ";Length=" + bytesRead); response = executeRequest(Request.Post(seedChunkUri).bodyStream( new ByteArrayInputStream(buffer, 0, bytesRead), ContentType.APPLICATION_OCTET_STREAM)) .returnResponse(); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new IOException("Unable to upload file. " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase()); } chunkIndex++; } } return md; }
From source file:org.kie.remote.tests.base.RestUtil.java
public static <T> T postEntity(URL deploymentUrl, String relativeUrl, String mediaType, int status, String user, String password, double timeoutInSecs, Object entity, Class<T>... responseTypes) { String uriStr = createBaseUriString(deploymentUrl, relativeUrl); ResponseHandler<T> rh = createResponseHandler(mediaType, status, responseTypes); String entityStr = ((AbstractResponseHandler) rh).serialize(entity); HttpEntity bodyEntity = null;//from w w w. j a va 2 s.c o m try { bodyEntity = new StringEntity(entityStr); } catch (UnsupportedEncodingException uee) { failAndLog("Unable to encode serialized " + entity.getClass().getSimpleName() + " entity", uee); } // @formatter:off Request request = Request.Post(uriStr).body(bodyEntity) .addHeader(HttpHeaders.CONTENT_TYPE, mediaType.toString()) .addHeader(HttpHeaders.ACCEPT, mediaType.toString()) .addHeader(HttpHeaders.AUTHORIZATION, basicAuthenticationHeader(user, password)); // @formatter:on Response resp = null; long before = 0, after = 0; try { logOp("POST", entity, uriStr); before = System.currentTimeMillis(); resp = request.execute(); after = System.currentTimeMillis(); } catch (Exception e) { failAndLog("[GET] " + uriStr, e); } long duration = after - before; assertTrue("Timeout exceeded " + timeoutInSecs + " secs: " + ((double) duration / 1000d) + " secs", duration < timeoutInSecs * 1000); try { return resp.handleResponse(rh); } catch (Exception e) { failAndLog("Failed retrieving response from [GET] " + uriStr, e); } // never happens return null; }
From source file:com.softinstigate.restheart.integrationtest.SecurityIT.java
@Test public void testPostAsAdmin() throws Exception { // *** POST coll1 Response resp = adminExecutor.execute(Request.Post(collection1Uri).bodyString("{a:1}", halCT) .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE)); check("check post coll1 as admin", resp, HttpStatus.SC_CREATED); // *** POST coll2 resp = adminExecutor.execute(Request.Post(collection2Uri).bodyString("{a:1}", halCT) .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE)); check("check post coll2b asadmin", resp, HttpStatus.SC_CREATED); }
From source file:us.nineworlds.plex.rest.PlexappFactory.java
/** * Given a resource's URL, read and return the serialized MediaContainer * @param resourceURL// w ww . jav a 2 s . c om * @return * @throws MalformedURLException * @throws IOException * @throws Exception */ protected Request generateRequest(String url, boolean get) { Request r = null; if (get) r = Request.Get(url); else r = Request.Post(url); return r.addHeader("X-Plex-Client-Identifier", config.getClientIdentifier()) .addHeader("X-Plex-Product", config.getProduct()) .addHeader("X-Plex-Version", config.getProductVersion()) .addHeader("X-Plex-Device", config.getDevice()) .addHeader("X-Plex-Device-Name", config.getDeviceName()).addHeader("Cache-Control", "max-age=0"); }
From source file:com.twosigma.beaker.NamespaceClient.java
private boolean runBooleanRequest(String urlfragment, Form postdata) throws ClientProtocolException, IOException { String reply = Request.Post(ctrlUrlBase + urlfragment).addHeader("Authorization", auth) .bodyForm(postdata.build()).execute().returnContent().asString(); return objectMapper.get().readValue(reply, Boolean.class); }
From source file:com.qwazr.search.index.IndexSingleClient.java
@Override public List<TermDefinition> testAnalyzer(String schema_name, String index_name, String analyzer_name, String text) {//from w ww . j av a 2s . c o m UBuilder uriBuilder = new UBuilder("/indexes/", schema_name, "/", index_name, "/analyzers/", analyzer_name); Request request = Request.Post(uriBuilder.build()); return commonServiceRequest(request, text, null, TermDefinition.MapListTermDefinitionRef, 200); }
From source file:org.biopax.validator.BiopaxValidatorClient.java
private String location(final String url) throws IOException { String location = url; //initially the same // discover actual location, avoid going in circles: int i = 0;/*w w w . j av a 2s .com*/ for (String loc = url; loc != null && i < 5; i++) { //do POST for location (Location header present if there's a 301/302/307 redirect on the way) loc = Request.Post(loc).execute().handleResponse(new ResponseHandler<String>() { public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException { Header header = httpResponse.getLastHeader("Location"); // System.out.println("header=" + header); return (header != null) ? header.getValue().trim() : null; } }); if (loc != null) { location = loc; log.info("BioPAX Validator location: " + loc); } } return location; }
From source file:org.mule.test.construct.FlowRefTestCase.java
@Test public void nonBlockingFlowRefErrorHandling() throws Exception { Response response = Request .Post(String.format("http://localhost:%s/%s", port.getNumber(), "nonBlockingFlowRefErrorHandling")) .connectTimeout(RECEIVE_TIMEOUT).bodyString(TEST_MESSAGE, ContentType.TEXT_PLAIN).execute(); HttpResponse httpResponse = response.returnResponse(); assertThat(httpResponse.getStatusLine().getStatusCode(), is(200)); assertThat(IOUtils.toString(httpResponse.getEntity().getContent()), is(ERROR_MESSAGE)); }