List of usage examples for org.apache.http.client.methods RequestBuilder post
public static RequestBuilder post()
From source file:sft.LoginAndBookSFT.java
public void startBooking() throws URISyntaxException, MalformedURLException, ProtocolException, IOException { final BasicCookieStore cookieStore = new BasicCookieStore(); final CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); try {// w ww. j av a2 s. c om // get cookie final HttpGet httpget = new HttpGet("https://sft.ticketack.com"); final CloseableHttpResponse response1 = httpclient.execute(httpget); try { final HttpEntity entity = response1.getEntity(); System.out.println("Login form get: " + response1.getStatusLine()); EntityUtils.consume(entity); System.out.println("Initial set of cookies:"); final List<Cookie> _cookies = cookieStore.getCookies(); if (_cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < _cookies.size(); i++) { System.out.println("- " + _cookies.get(i).toString()); } } } finally { response1.close(); } // login final HttpUriRequest login = RequestBuilder.post() .setUri(new URI("https://sft.ticketack.com/ticket/view/")) .addParameter("ticket_number", username).addParameter("ticket_key", password).build(); final CloseableHttpResponse response2 = httpclient.execute(login); try { final HttpEntity entity = response2.getEntity(); System.out.println("Login form get: " + response2.getStatusLine()); EntityUtils.consume(entity); System.out.println("Post logon cookies:"); final List<Cookie> cookies = cookieStore.getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { // System.out.println("- " + cookies.get(i).toString()); } } } finally { response2.close(); } } finally { httpclient.close(); } final Cookie _cookie = cookieStore.getCookies().get(0); final String mightyCooke = "PHPSESSID=" + _cookie.getValue(); for (final String _booking : bookings) { // get free seatings // json https://sft.ticketack.com/screening/infos_json/02c101f9-c62a-445e-ad72-19fb32db34c0 final String _json = doGet(mightyCooke, _booking, "https://sft.ticketack.com/screening/infos_json/"); final Gson gson = new Gson(); final Example _allInfos = gson.fromJson(_json, Example.class); if (_allInfos.getCinemaHall().getMap() != null) { final String _mySeat = getMeAFreeSeat(_json); // book on seating // 02c101f9-c62a-445e-ad72-19fb32db34c0?format=json&overbook=false&seat=Parkett%20Rechts:1:16 try { if (_mySeat != null) doGet(mightyCooke, _booking + "?format=json&overbook=true&seat=" + URLEncoder.encode(_mySeat, "UTF-8"), "https://sft.ticketack.com/screening/book_on_ticket/"); } catch (final MalformedURLException exception) { System.err.println("Error: " + exception.getMessage()); } catch (final ProtocolException exception) { System.err.println("Error: " + exception.getMessage()); } catch (final UnsupportedEncodingException exception) { System.err.println("Error: " + exception.getMessage()); } catch (final IOException exception) { System.err.println("Error: " + exception.getMessage()); } System.out.println("booking (seat) done for: " + _booking); } else { // book // https://sft.ticketack.com/screening/book_on_ticket/76c039cc-d1d5-40a1-9a5d-2b1cd4c47799 // Cookie:PHPSESSID=s1a6a8casfhidfq68tqn2cb565 doGet(mightyCooke, _booking, "https://sft.ticketack.com/screening/book_on_ticket/"); System.out.println("booking done for: " + _booking); } } System.out.println("All done!"); }
From source file:edu.mit.scratch.Scratch.java
public static ScratchSession createSession(final String username, String password) throws ScratchLoginException { try {/*from w ww . j a va 2s. c o m*/ final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT) // Changed due to deprecation .build(); final CookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en"); lang.setDomain(".scratch.mit.edu"); lang.setPath("/"); cookieStore.addCookie(lang); final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig) .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build(); CloseableHttpResponse resp; final HttpUriRequest csrf = RequestBuilder.get().setUri("https://scratch.mit.edu/csrf_token/") .addHeader("Accept", "*/*").addHeader("Referer", "https://scratch.mit.edu") .addHeader("X-Requested-With", "XMLHttpRequest").build(); resp = httpClient.execute(csrf); resp.close(); String csrfToken = null; for (final Cookie c : cookieStore.getCookies()) if (c.getName().equals("scratchcsrftoken")) csrfToken = c.getValue(); final JSONObject loginObj = new JSONObject(); loginObj.put("username", username); loginObj.put("password", password); loginObj.put("captcha_challenge", ""); loginObj.put("captcha_response", ""); loginObj.put("embed_captcha", false); loginObj.put("timezone", "America/New_York"); loginObj.put("csrfmiddlewaretoken", csrfToken); final HttpUriRequest login = RequestBuilder.post().setUri("https://scratch.mit.edu/accounts/login/") .addHeader("Accept", "application/json, text/javascript, */*; q=0.01") .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu") .addHeader("Accept-Encoding", "gzip, deflate").addHeader("Accept-Language", "en-US,en;q=0.8") .addHeader("Content-Type", "application/json").addHeader("X-Requested-With", "XMLHttpRequest") .addHeader("X-CSRFToken", csrfToken).setEntity(new StringEntity(loginObj.toString())).build(); resp = httpClient.execute(login); password = null; final BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); final StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) result.append(line); final JSONObject jsonOBJ = new JSONObject( result.toString().substring(1, result.toString().length() - 1)); if ((int) jsonOBJ.get("success") != 1) throw new ScratchLoginException(); String ssi = null; String sct = null; String e = null; final Header[] headers = resp.getAllHeaders(); for (final Header header : headers) if (header.getName().equals("Set-Cookie")) { final String value = header.getValue(); final String[] split = value.split(Pattern.quote("; ")); for (final String s : split) { if (s.contains("=")) { final String[] split2 = s.split(Pattern.quote("=")); final String key = split2[0]; final String val = split2[1]; if (key.equals("scratchsessionsid")) ssi = val; else if (key.equals("scratchcsrftoken")) sct = val; else if (key.equals("expires")) e = val; } } } resp.close(); return new ScratchSession(ssi, sct, e, username); } catch (final IOException e) { e.printStackTrace(); throw new ScratchLoginException(); } }
From source file:org.apache.trafficcontrol.client.RestApiSession.java
public CompletableFuture<HttpResponse> post(String url, String body) { final HttpEntity e = new StringEntity(body, Charsets.UTF_8); return execute(RequestBuilder.post().setUri(url).setEntity(e)); }
From source file:edu.mit.scratch.ScratchSession.java
public void logout() throws ScratchUserException { final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY) .build();// w ww .j a v a2 s. c o m final CookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en"); final BasicClientCookie sessid = new BasicClientCookie("scratchsessionsid", this.getSessionID()); final BasicClientCookie token = new BasicClientCookie("scratchcsrftoken", this.getCSRFToken()); final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true"); lang.setDomain(".scratch.mit.edu"); lang.setPath("/"); sessid.setDomain(".scratch.mit.edu"); sessid.setPath("/"); token.setDomain(".scratch.mit.edu"); token.setPath("/"); debug.setDomain(".scratch.mit.edu"); debug.setPath("/"); cookieStore.addCookie(lang); cookieStore.addCookie(sessid); cookieStore.addCookie(token); cookieStore.addCookie(debug); final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig) .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64)" + " AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/" + "537.36") .setDefaultCookieStore(cookieStore).build(); CloseableHttpResponse resp; final JSONObject loginObj = new JSONObject(); loginObj.put("csrftoken", this.getCSRFToken()); try { final HttpUriRequest logout = RequestBuilder.post().setUri("https://scratch.mit.edu/accounts/logout/") .addHeader("Accept", "application/json, text/javascript, */*; q=0.01") .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu") .addHeader("Accept-Encoding", "gzip, deflate").addHeader("Accept-Language", "en-US,en;q=0.8") .addHeader("Content-Type", "application/json").addHeader("X-Requested-With", "XMLHttpRequest") .addHeader("X-CSRFToken", this.getCSRFToken()).setEntity(new StringEntity(loginObj.toString())) .build(); resp = httpClient.execute(logout); } catch (final Exception e) { throw new ScratchUserException(); } this.session_id = null; this.token = null; this.expires = null; this.username = null; }
From source file:org.eclipse.vorto.repository.RestClient.java
@SuppressWarnings("restriction") public <Result> Result executePost(String query, HttpEntity content, final Function<String, Result> responseConverter) throws ClientProtocolException, IOException { CloseableHttpClient client = HttpClients.custom().build(); HttpUriRequest request = RequestBuilder.post().setConfig(createProxyConfiguration()) .setUri(createQuery(query)).addHeader(createSecurityHeader()).setEntity(content).build(); return client.execute(request, new ResponseHandler<Result>() { @Override/*from ww w . j a v a 2 s .c o m*/ public Result handleResponse(HttpResponse response) throws ClientProtocolException, IOException { return responseConverter.apply(IOUtils.toString(response.getEntity().getContent())); } }); }
From source file:org.cloudfoundry.identity.uaa.integration.FormLoginIntegrationTests.java
@Test public void testSuccessfulAuthenticationFlow() throws Exception { //request home page / String location = serverRunning.getBaseUrl() + "/"; HttpGet httpget = new HttpGet(location); CloseableHttpResponse response = httpclient.execute(httpget); assertEquals(OK.value(), response.getStatusLine().getStatusCode()); String body = EntityUtils.toString(response.getEntity()); EntityUtils.consume(response.getEntity()); response.close();// ww w . j a v a2 s .c om httpget.completed(); assertTrue(body.contains("/login.do")); assertTrue(body.contains("username")); assertTrue(body.contains("password")); String csrf = IntegrationTestUtils.extractCookieCsrf(body); HttpUriRequest loginPost = RequestBuilder.post().setUri(serverRunning.getBaseUrl() + "/login.do") .addParameter("username", testAccounts.getUserName()) .addParameter("password", testAccounts.getPassword()) .addParameter(CookieBasedCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, csrf).build(); response = httpclient.execute(loginPost); assertEquals(FOUND.value(), response.getStatusLine().getStatusCode()); location = response.getFirstHeader("Location").getValue(); response.close(); httpget = new HttpGet(location); response = httpclient.execute(httpget); assertEquals(OK.value(), response.getStatusLine().getStatusCode()); body = EntityUtils.toString(response.getEntity()); response.close(); assertTrue(body.contains("Sign Out")); }
From source file:cf.spring.servicebroker.CatalogTest.java
@Test public void postToCatalog() throws Exception { final SpringApplication application = new SpringApplication(EmptyServiceBrokerCatalog.class); try (ConfigurableApplicationContext context = application.run(); CloseableHttpClient client = HttpClients.createDefault()) { final HttpUriRequest catalogRequest = RequestBuilder.post() .setUri("http://localhost:8080" + Constants.CATALOG_URI).build(); final CloseableHttpResponse response = client.execute(catalogRequest); assertEquals(response.getStatusLine().getStatusCode(), 405); }//ww w . j a va 2s .c om }
From source file:org.dasein.cloud.azure.platform.AzureSQLDatabaseSupportRequests.java
public RequestBuilder createDatabase(String serverName, DatabaseServiceResourceModel dbToCreate) { RequestBuilder requestBuilder = RequestBuilder.post(); addAzureCommonHeaders(requestBuilder); requestBuilder.setUri(// w w w. j a v a 2 s . co m String.format(RESOURCE_DATABASES, this.provider.getContext().getAccountNumber(), serverName)); requestBuilder.setEntity(new DaseinObjectToXmlEntity<DatabaseServiceResourceModel>(dbToCreate)); return requestBuilder; }
From source file:org.esbtools.message.admin.rest.ESBMessageAdminServiceClient.java
@Override public void persistError(EsbMessage esbMessage) throws IOException { doRequest(RequestBuilder.post().setUri(serviceUrl("/persist")).setEntity(asEntity(esbMessage)).build()); }
From source file:org.keycloak.adapters.authorization.cip.HttpClaimInformationPointProvider.java
private InputStream executeRequest(HttpFacade httpFacade) { String method = config.get("method").toString(); if (method == null) { method = "GET"; }//from w ww. ja v a 2 s .c om RequestBuilder builder = null; if ("GET".equalsIgnoreCase(method)) { builder = RequestBuilder.get(); } else { builder = RequestBuilder.post(); } builder.setUri(config.get("url").toString()); byte[] bytes = new byte[0]; try { setParameters(builder, httpFacade); if (config.containsKey("headers")) { setHeaders(builder, httpFacade); } HttpResponse response = httpClient.execute(builder.build()); HttpEntity entity = response.getEntity(); if (entity != null) { bytes = EntityUtils.toByteArray(entity); } StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode < 200 || statusCode >= 300) { throw new HttpResponseException( "Unexpected response from server: " + statusCode + " / " + statusLine.getReasonPhrase(), statusCode, statusLine.getReasonPhrase(), bytes); } return new ByteArrayInputStream(bytes); } catch (Exception cause) { try { throw new RuntimeException( "Error executing http method [" + builder + "]. Response : " + StreamUtil.readString(new ByteArrayInputStream(bytes), Charset.forName("UTF-8")), cause); } catch (Exception e) { throw new RuntimeException("Error executing http method [" + builder + "]", cause); } } }