List of usage examples for org.apache.http.client.methods CloseableHttpResponse close
public void close() throws IOException;
From source file:edu.mit.scratch.Scratch.java
public static ScratchSession register(final String username, final String password, final String gender, final int birthMonth, final String birthYear, final String country, final String email) throws ScratchUserException { // Long if statement to verify all fields are valid if ((username.length() < 3) || (username.length() > 20) || (password.length() < 6) || (gender.length() < 2) || (birthMonth < 1) || (birthMonth > 12) || (birthYear.length() != 4) || (country.length() == 0) || (email.length() < 5)) { throw new ScratchUserException(); // TDL: Specify reason for failure } else {/*from w ww.j a v a 2 s.com*/ try { final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT) .build(); final CookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en"); lang.setDomain(".scratch.mit.edu"); lang.setPath("/"); cookieStore.addCookie(lang); 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(); try { resp = httpClient.execute(csrf); } catch (final IOException e) { e.printStackTrace(); throw new ScratchUserException(); } try { resp.close(); } catch (final IOException e) { throw new ScratchUserException(); } String csrfToken = null; for (final Cookie c : cookieStore.getCookies()) if (c.getName().equals("scratchcsrftoken")) csrfToken = c.getValue(); /* * try { * username = URLEncoder.encode(username, "UTF-8"); * password = URLEncoder.encode(password, "UTF-8"); * birthMonth = Integer.parseInt(URLEncoder.encode("" + * birthMonth, "UTF-8")); * birthYear = URLEncoder.encode(birthYear, "UTF-8"); * gender = URLEncoder.encode(gender, "UTF-8"); * country = URLEncoder.encode(country, "UTF-8"); * email = URLEncoder.encode(email, "UTF-8"); * } catch (UnsupportedEncodingException e1) { * e1.printStackTrace(); * } */ final BasicClientCookie csrfCookie = new BasicClientCookie("scratchcsrftoken", csrfToken); csrfCookie.setDomain(".scratch.mit.edu"); csrfCookie.setPath("/"); cookieStore.addCookie(csrfCookie); final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true"); debug.setDomain(".scratch.mit.edu"); debug.setPath("/"); cookieStore.addCookie(debug); httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig) .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build(); /* * final String data = "username=" + username + "&password=" + * password + "&birth_month=" + birthMonth + "&birth_year=" + * birthYear + "&gender=" + gender + "&country=" + country + * "&email=" + email + * "&is_robot=false&should_generate_admin_ticket=false&usernames_and_messages=%3Ctable+class%3D'banhistory'%3E%0A++++%3Cthead%3E%0A++++++++%3Ctr%3E%0A++++++++++++%3Ctd%3EAccount%3C%2Ftd%3E%0A++++++++++++%3Ctd%3EEmail%3C%2Ftd%3E%0A++++++++++++%3Ctd%3EReason%3C%2Ftd%3E%0A++++++++++++%3Ctd%3EDate%3C%2Ftd%3E%0A++++++++%3C%2Ftr%3E%0A++++%3C%2Fthead%3E%0A++++%0A%3C%2Ftable%3E%0A&csrfmiddlewaretoken=" * + csrfToken; * System.out.println(data); */ final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("birth_month", birthMonth + "", ContentType.TEXT_PLAIN); builder.addTextBody("birth_year", birthYear, ContentType.TEXT_PLAIN); builder.addTextBody("country", country, ContentType.TEXT_PLAIN); builder.addTextBody("csrfmiddlewaretoken", csrfToken, ContentType.TEXT_PLAIN); builder.addTextBody("email", email, ContentType.TEXT_PLAIN); builder.addTextBody("gender", gender, ContentType.TEXT_PLAIN); builder.addTextBody("is_robot", "false", ContentType.TEXT_PLAIN); builder.addTextBody("password", password, ContentType.TEXT_PLAIN); builder.addTextBody("should_generate_admin_ticket", "false", ContentType.TEXT_PLAIN); builder.addTextBody("username", username, ContentType.TEXT_PLAIN); builder.addTextBody("usernames_and_messages", "<table class=\"banhistory\"> <thead> <tr> <td>Account</td> <td>Email</td> <td>Reason</td> <td>Date</td> </tr> </thead> </table>", ContentType.TEXT_PLAIN); final HttpUriRequest createAccount = RequestBuilder.post() .setUri("https://scratch.mit.edu/accounts/register_new_user/") .addHeader("Accept", "application/json, text/javascript, */*; q=0.01") .addHeader("Referer", "https://scratch.mit.edu/accounts/standalone-registration/") .addHeader("Origin", "https://scratch.mit.edu") .addHeader("Accept-Encoding", "gzip, deflate").addHeader("DNT", "1") .addHeader("Accept-Language", "en-US,en;q=0.8") .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8") .addHeader("X-Requested-With", "XMLHttpRequest").addHeader("X-CSRFToken", csrfToken) .addHeader("X-DevTools-Emulate-Network-Conditions-Client-Id", "54255D9A-9771-4CAC-9052-50C8AB7469E0") .setEntity(builder.build()).build(); resp = httpClient.execute(createAccount); System.out.println("REGISTER:" + resp.getStatusLine()); 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); System.out.println("exact:" + result.toString() + "\n" + resp.getStatusLine().getReasonPhrase() + "\n" + resp.getStatusLine()); if (resp.getStatusLine().getStatusCode() != 200) throw new ScratchUserException(); resp.close(); } catch (final Exception e) { e.printStackTrace(); throw new ScratchUserException(); } try { return Scratch.createSession(username, password); } catch (final Exception e) { e.printStackTrace(); throw new ScratchUserException(); } } }
From source file:org.wuspba.ctams.ws.ITBandMemberController.java
private static void add(BandMember m) throws Exception { CTAMSDocument doc = new CTAMSDocument(); doc.getPeople().add(m.getPerson());//from w w w .ja v a 2 s . co m doc.getBandMembers().add(m); String xml = XMLUtils.marshal(doc); CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); HttpPost httpPost = new HttpPost(uri); StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML); CloseableHttpResponse response = null; try { httpPost.setEntity(xmlEntity); response = httpclient.execute(httpPost); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); doc = IntegrationTestUtils.convertEntity(responseEntity); m.setId(doc.getBandMembers().get(0).getId()); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } }
From source file:org.wuspba.ctams.ws.ITBandContestEntryController.java
private static void add() throws Exception { ITVenueController.add();/*from w ww . j a va 2 s. c o m*/ ITJudgeController.add(); ITBandController.add(); ITBandContestController.add(); CTAMSDocument doc = new CTAMSDocument(); doc.getVenues().add(TestFixture.INSTANCE.venue); doc.getJudges().add(TestFixture.INSTANCE.judgeAndy); doc.getJudges().add(TestFixture.INSTANCE.judgeJamie); doc.getJudges().add(TestFixture.INSTANCE.judgeBob); doc.getJudges().add(TestFixture.INSTANCE.judgeEoin); doc.getBandContests().add(TestFixture.INSTANCE.bandContest); doc.getBands().add(TestFixture.INSTANCE.skye); doc.getBandContestEntry().add(TestFixture.INSTANCE.bandContestEntry); String xml = XMLUtils.marshal(doc); CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); HttpPost httpPost = new HttpPost(uri); StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML); CloseableHttpResponse response = null; try { httpPost.setEntity(xmlEntity); response = httpclient.execute(httpPost); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); doc = IntegrationTestUtils.convertEntity(responseEntity); TestFixture.INSTANCE.bandContestEntry.setId(doc.getBandContestEntry().get(0).getId()); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } }
From source file:org.wuspba.ctams.ws.ITSoloContestEntryController.java
private static void add() throws Exception { ITVenueController.add();/*from www . ja v a 2 s .c o m*/ ITJudgeController.add(); ITPersonController.add(); ITSoloContestController.add(); CTAMSDocument doc = new CTAMSDocument(); doc.getVenues().add(TestFixture.INSTANCE.venue); doc.getJudges().add(TestFixture.INSTANCE.judgeAndy); doc.getJudges().add(TestFixture.INSTANCE.judgeJamie); doc.getJudges().add(TestFixture.INSTANCE.judgeBob); doc.getJudges().add(TestFixture.INSTANCE.judgeEoin); doc.getSoloContests().add(TestFixture.INSTANCE.soloContest); doc.getPeople().add(TestFixture.INSTANCE.elaine); doc.getSoloContestEntry().add(TestFixture.INSTANCE.soloContestEntry); String xml = XMLUtils.marshal(doc); CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); HttpPost httpPost = new HttpPost(uri); StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML); CloseableHttpResponse response = null; try { httpPost.setEntity(xmlEntity); response = httpclient.execute(httpPost); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); doc = IntegrationTestUtils.convertEntity(responseEntity); TestFixture.INSTANCE.soloContestEntry.setId(doc.getSoloContestEntry().get(0).getId()); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } }
From source file:au.org.ncallister.goodbudget.tools.coms.GoodBudgetSession.java
public void login(String username, String password) throws IOException { if (client == null) { client = HttpClients.createDefault(); }//from ww w . j a v a2s.c o m HttpPost post = new HttpPost(BASE_URI.resolve(PATH_LOGIN)); // post.addHeader("Content-Type", "application/x-www-form-urlencoded"); List<NameValuePair> postContent = new ArrayList<>(); postContent.add(new BasicNameValuePair("_username", username)); postContent.add(new BasicNameValuePair("_password", password)); post.setEntity(new UrlEncodedFormEntity(postContent)); CloseableHttpResponse response = client.execute(post, sessionContext); response.close(); }
From source file:io.github.thred.climatetray.ClimateTrayUtils.java
public static BuildInfo performBuildInfoRequest() { try {/* w w w . j av a 2 s.c o m*/ CloseableHttpClient client = ClimateTray.PREFERENCES.getProxySettings().createHttpClient(); HttpGet request = new HttpGet(BUILD_INFO_URL); CloseableHttpResponse response; try { response = client.execute(request); } catch (IOException e) { ClimateTray.LOG.warn("Failed to request build information from \"%s\".", e, BUILD_INFO_URL); consumeUpdateFailed(); return null; } try { int status = response.getStatusLine().getStatusCode(); if ((status >= 200) && (status < 300)) { try (InputStream in = response.getEntity().getContent()) { BuildInfo buildInfo = BuildInfo.create(in); ClimateTray.LOG.info("Build Information: %s", buildInfo); return buildInfo; } } else { ClimateTray.LOG.warn("Request to \"%s\" failed with error %d.", BUILD_INFO_URL, status); consumeUpdateFailed(); } } finally { response.close(); } } catch (Exception e) { ClimateTray.LOG.warn("Failed to request build information.", e); } return null; }
From source file:org.jboss.pnc.auth.client.SimpleOAuthConnect.java
private static String[] connect(String url, Map<String, String> urlParams) throws ClientProtocolException, IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); // add header httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); List<BasicNameValuePair> urlParameters = new ArrayList<BasicNameValuePair>(); for (String key : urlParams.keySet()) { urlParameters.add(new BasicNameValuePair(key, urlParams.get(key))); }/*from w w w. jav a 2 s. c o m*/ httpPost.setEntity(new UrlEncodedFormEntity(urlParameters)); CloseableHttpResponse response = httpclient.execute(httpPost); String refreshToken = ""; String accessToken = ""; try { BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { if (line.contains("refresh_token")) { String[] respContent = line.split(","); for (int i = 0; i < respContent.length; i++) { String split = respContent[i]; if (split.contains("refresh_token")) { refreshToken = split.split(":")[1].substring(1, split.split(":")[1].length() - 1); } if (split.contains("access_token")) { accessToken = split.split(":")[1].substring(1, split.split(":")[1].length() - 1); } } } } } finally { response.close(); } return new String[] { accessToken, refreshToken }; }
From source file:org.helm.notation2.wsadapter.MonomerWSLoader.java
/** * Loads the monomer categories using the URL configured in * {@code MonomerStoreConfiguration}./*from ww w.j a va 2 s . c o m*/ * * @return List containing monomer categories * * @throws IOException * @throws URISyntaxException */ public static List<CategorizedMonomer> loadMonomerCategorization() throws IOException, URISyntaxException { List<CategorizedMonomer> config = new LinkedList<CategorizedMonomer>(); CloseableHttpClient httpclient = HttpClients.createDefault(); // There is no need to provide user credentials // HttpClient will attempt to access current user security context // through Windows platform specific methods via JNI. CloseableHttpResponse response = null; try { response = WSAdapterUtils.getResource( MonomerStoreConfiguration.getInstance().getWebserviceEditorCategorizationFullURL()); LOG.debug(response.getStatusLine().toString()); JsonFactory jsonf = new JsonFactory(); InputStream instream = response.getEntity().getContent(); JsonParser jsonParser = jsonf.createJsonParser(instream); config = deserializeEditorCategorizationConfig(jsonParser); LOG.debug(config.size() + " categorization info entries loaded"); EntityUtils.consume(response.getEntity()); } finally { if (response != null) { response.close(); } if (httpclient != null) { httpclient.close(); } } return config; }
From source file:org.wuspba.ctams.ws.ITVenueController.java
protected static void add() throws Exception { CTAMSDocument doc = new CTAMSDocument(); doc.getVenues().add(TestFixture.INSTANCE.venue); String xml = XMLUtils.marshal(doc); CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); HttpPost httpPost = new HttpPost(uri); StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML); CloseableHttpResponse response = null; try {//from w w w.j a v a 2s . c o m httpPost.setEntity(xmlEntity); response = httpclient.execute(httpPost); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); doc = IntegrationTestUtils.convertEntity(responseEntity); TestFixture.INSTANCE.venue.setId(doc.getVenues().get(0).getId()); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } }
From source file:org.earthtime.archivingTools.IEDACredentialsValidator.java
private static Document HTTP_PostAndResponse(String userName, String password, String credentialsService) { Document doc = null;//from w ww . ja va 2 s .c o m Map<String, String> dataToPost = new HashMap<>(); dataToPost.put("username", userName); dataToPost.put("password", password); CloseableHttpClient httpclient = HttpClients.createDefault(); org.apache.http.client.methods.HttpPost httpPost = new HttpPost(credentialsService); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("username", userName)); nameValuePairs.add(new BasicNameValuePair("password", password)); CloseableHttpResponse httpResponse = null; try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httpResponse = httpclient.execute(httpPost); HttpEntity myEntity = httpResponse.getEntity(); InputStream response = myEntity.getContent(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); try { doc = factory.newDocumentBuilder().parse(response); //System.out.println("CCCC" + doc.getElementsByTagName("valid").item(0).getTextContent().trim()); } catch (ParserConfigurationException | SAXException | IOException parserConfigurationException) { System.out.println("PARSE error " + parserConfigurationException.getMessage()); } EntityUtils.consume(myEntity); } catch (IOException iOException) { } finally { try { httpResponse.close(); } catch (IOException iOException) { } } return doc; }