List of usage examples for org.apache.http.impl.client CloseableHttpClient execute
public CloseableHttpResponse execute(final HttpUriRequest request) throws IOException, ClientProtocolException
From source file:com.gemstone.gemfire.rest.internal.web.controllers.RestAPIsAndInterOpsDUnitTest.java
public static void fetchRestServerEndpoints(String restEndpoint) { HttpGet get = new HttpGet(restEndpoint + "/servers"); get.addHeader("Content-Type", "application/json"); get.addHeader("Accept", "application/json"); CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response;/*w ww. ja va 2 s .com*/ try { response = httpclient.execute(get); HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; StringBuffer str = new StringBuffer(); while ((line = reader.readLine()) != null) { str.append(line); } //validate the satus code assertEquals(response.getStatusLine().getStatusCode(), 200); if (response.getStatusLine().getStatusCode() == 200) { JSONArray jsonArray = new JSONArray(str.toString()); //verify total number of REST service endpoints in DS assertEquals(jsonArray.length(), 2); } } catch (ClientProtocolException e) { e.printStackTrace(); fail(" Rest Request should not have thrown ClientProtocolException!"); } catch (IOException e) { e.printStackTrace(); fail(" Rest Request should not have thrown IOException!"); } catch (JSONException e) { e.printStackTrace(); fail(" Rest Request should not have thrown JSONException!"); } }
From source file:com.ibm.devops.notification.MessageHandler.java
public static void postToWebhook(String webhook, boolean deployableMessage, JSONObject message, PrintStream printStream) { //check webhook if (Util.isNullOrEmpty(webhook)) { printStream.println("[IBM Cloud DevOps] IBM_CLOUD_DEVOPS_WEBHOOK_URL not set."); printStream.println("[IBM Cloud DevOps] Error: Failed to notify OTC."); } else {// w w w .j a v a 2s . c o m // set a 5 seconds timeout RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(5000) .setConnectTimeout(5000).setConnectionRequestTimeout(5000).build(); CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig) .build(); HttpPost postMethod = new HttpPost(webhook); try { StringEntity data = new StringEntity(message.toString()); postMethod.setEntity(data); postMethod = Proxy.addProxyInformation(postMethod); postMethod.addHeader("Content-Type", "application/json"); if (deployableMessage) { postMethod.addHeader("x-create-connection", "true"); printStream.println("[IBM Cloud DevOps] Sending Deployable Mapping message to webhook:"); printStream.println(message); } CloseableHttpResponse response = httpClient.execute(postMethod); if (response.getStatusLine().toString().matches(".*2([0-9]{2}).*")) { printStream.println("[IBM Cloud DevOps] Message successfully posted to webhook."); } else { printStream.println( "[IBM Cloud DevOps] Message failed, response status: " + response.getStatusLine()); } } catch (IOException e) { printStream.println("[IBM Cloud DevOps] IOException, could not post to webhook:"); e.printStackTrace(printStream); } } }
From source file:com.worldsmostinterestinginfographic.util.OAuth2Utils.java
/** * Make a protected resource request at the given endpoint with the given access token. * * This method will attempt to access the protected resource with the given access token using the authorization * request header field method. If successful, the full response string will be returned. * * @param resourceEndpoint The endpoint of the protected resource to access * @param accessToken A valid access token with the necessary scopes required to access the protected resource * @return The result string returned in response to the request to access the protected resource with the given token *///from w ww .j a va 2 s . c om public static String makeProtectedResourceRequest(String resourceEndpoint, String accessToken) { CloseableHttpClient httpClient = HttpClients.createDefault(); try { httpClient = HttpClients.createDefault(); // Add authorization header to POST request HttpPost httpPost = new HttpPost(resourceEndpoint); httpPost.addHeader("Authorization", "Bearer " + accessToken); /* * Note: The addition of the "method=get" URL-encoded form parameter is necessary for the Facebook Graph APIs. * Other OAuth 2 providers may not require this, and some may even reject it. */ List<NameValuePair> urlParameters = new ArrayList<>(); urlParameters.add(new BasicNameValuePair("method", "get")); httpPost.setEntity(new UrlEncodedFormEntity(urlParameters)); // Make the call HttpResponse httpResponse = httpClient.execute(httpPost); // Process the response String response = ""; String currentLine; BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(httpResponse.getEntity().getContent())); while ((currentLine = bufferedReader.readLine()) != null) { response += currentLine; } return response; } catch (IOException e) { log.severe("Fatal exception occurred while making the protected resource request (access token " + LoggingUtils.anonymize(accessToken) + "): " + e.getMessage()); e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { log.severe("Fatal exception occurred while closing HTTP client connection (access token=" + LoggingUtils.anonymize(accessToken) + "): " + e.getMessage()); e.printStackTrace(); } } return null; }
From source file:com.jaspersoft.studio.community.RESTCommunityHelper.java
/** * Executes the authentication to the Jaspersoft community in order to * retrieve the session cookie to use later for all other operations. * // w ww.j a v a 2s . c om * @param httpclient * the http client * * @param cookieStore * the Cookie Store instance * @param username * the community user name (or email) * @param password * the community user password * @return the authentication cookie if able to retrieve it, * <code>null</code> otherwise * @throws CommunityAPIException */ public static Cookie getAuthenticationCookie(CloseableHttpClient httpclient, CookieStore cookieStore, String username, String password) throws CommunityAPIException { try { HttpPost loginPOST = new HttpPost(CommunityConstants.LOGIN_URL); EntityBuilder loginEntity = EntityBuilder.create(); loginEntity.setText("{ \"username\": \"" + username + "\", \"password\":\"" + password + "\" }"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ loginEntity.setContentType(ContentType.create(CommunityConstants.JSON_CONTENT_TYPE)); loginEntity.setContentEncoding(CommunityConstants.REQUEST_CHARSET); loginPOST.setEntity(loginEntity.build()); CloseableHttpResponse resp = httpclient.execute(loginPOST); int httpRetCode = resp.getStatusLine().getStatusCode(); String responseBodyAsString = EntityUtils.toString(resp.getEntity()); if (HttpStatus.SC_OK == httpRetCode) { // Can proceed List<Cookie> cookies = cookieStore.getCookies(); Cookie authCookie = null; for (Cookie cookie : cookies) { if (cookie.getName().startsWith("SESS")) { //$NON-NLS-1$ authCookie = cookie; break; } } return authCookie; } else if (HttpStatus.SC_UNAUTHORIZED == httpRetCode) { // Unauthorized... wrong username or password CommunityAPIException unauthorizedEx = new CommunityAPIException( Messages.RESTCommunityHelper_WrongUsernamePasswordError); unauthorizedEx.setHttpStatusCode(httpRetCode); unauthorizedEx.setResponseBodyAsString(responseBodyAsString); throw unauthorizedEx; } else { // Some other problem occurred CommunityAPIException generalEx = new CommunityAPIException( Messages.RESTCommunityHelper_AuthInfoProblemsError); generalEx.setHttpStatusCode(httpRetCode); generalEx.setResponseBodyAsString(responseBodyAsString); throw generalEx; } } catch (UnsupportedEncodingException e) { JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_EncodingNotValidError, e); throw new CommunityAPIException(Messages.RESTCommunityHelper_AuthenticationError, e); } catch (IOException e) { JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_PostMethodIOError, e); throw new CommunityAPIException(Messages.RESTCommunityHelper_AuthenticationError, e); } }
From source file:utils.APIImporter.java
/** * Adding the API documents to the published API * @param folderPath folder path imported API folder * @param accessToken access token// ww w. ja va 2 s . c o m * @param uuid uuid of the created API */ private static void addAPIDocuments(String folderPath, String accessToken, String uuid) { String docSummaryLocation = folderPath + ImportExportConstants.DOCUMENT_FILE_LOCATION; try { //getting the list of documents String jsonContent = FileUtils.readFileToString(new File(docSummaryLocation)); JSONParser parser = new JSONParser(); JSONObject jsonObject = (JSONObject) parser.parse(jsonContent); JSONArray array = (JSONArray) jsonObject.get(ImportExportConstants.DOCUMENT_LIST); if (array.size() == 0) { String message = "Imported API doesn't have any documents to be publish"; log.warn(message); } else { for (Object anArray : array) { JSONObject obj = (JSONObject) anArray; //publishing each document String url = config.getPublisherUrl() + "apis/" + uuid + "/documents"; CloseableHttpClient client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate()); HttpPost request = new HttpPost(url); request.setEntity(new StringEntity(obj.toString(), ImportExportConstants.CHARSET)); request.setHeader(HttpHeaders.AUTHORIZATION, ImportExportConstants.CONSUMER_KEY_SEGMENT + " " + accessToken); request.setHeader(HttpHeaders.CONTENT_TYPE, ImportExportConstants.CONTENT_JSON); CloseableHttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() == Response.Status.CREATED.getStatusCode()) { String responseString = EntityUtils.toString(response.getEntity(), ImportExportConstants.CHARSET); String sourceType = ImportExportUtils.readJsonValues(responseString, ImportExportConstants.SOURCE_TYPE); if (sourceType.equalsIgnoreCase(ImportExportConstants.FILE_DOC_TYPE) || sourceType.equalsIgnoreCase(ImportExportConstants.INLINE_DOC_TYPE)) { addDocumentContent(folderPath, uuid, responseString, accessToken); } } else { String message = "Error occurred while publishing the API document " + obj.get(ImportExportConstants.DOC_NAME) + " " + response.getStatusLine(); log.warn(message); } } } } catch (IOException e) { errorMsg = "error occurred while adding the API documents"; log.error(errorMsg, e); } catch (ParseException e) { errorMsg = "error occurred importing the API documents"; log.error(errorMsg, e); } }
From source file:org.wuspba.ctams.ws.ITRosterController.java
private static void add(Roster roster) throws Exception { CTAMSDocument doc = new CTAMSDocument(); doc.getRosters().add(roster);/* w w w .ja v a 2 s . c o 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); roster.setId(doc.getRosters().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:com.ebixio.virtmus.stats.StatsLogger.java
/** * Check for new versions of VirtMus.//from w w w. j a v a2s .co m * @param installId The random ID identifying this install. * @param prevVersion The previous version of VirtMus installed. * @param statsEnabled Set to true if the user is participating in stats collection. */ private static void checkForNewVersion(long installId, String prevVersion, UploadStats statsEnabled) { final String urlStr = pref.get(Options.OptCheckVersionUrl, CHECK_VERSION); // Catch redirects. HttpRedirectStrategy httpRedirect = new HttpRedirectStrategy() { @Override public void handlePermanentRedirect(HttpRequest request, HttpResponse response, HttpUriRequest redirect) { if (!Utils.isNullOrEmpty(newUrl) && !newUrl.equals(urlStr)) { pref.put(Options.OptCheckVersionUrl, newUrl); } } }; // TODO: Use http://wiki.fasterxml.com/JacksonHome to avoid warnings? String postData = new JSONStringer().object().key("version").value(MainApp.VERSION) /* installId MUST be sent as string since JS on the server side only has 64-bit float values and can't represent all long int values, leading to truncation of some digits since the JS float mantisa has only 53 bits (not 64). See: http://www.2ality.com/2012/07/large-integers.html */ .key("installId").value(String.valueOf(installId)).key("prevVersion").value(prevVersion) .key("statsEnabled").value(statsEnabled.name()).endObject().toString(); try { CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(httpRedirect).build(); HttpPost post = new HttpPost(urlStr); addHttpHeaders(post); StringEntity entity = new StringEntity(postData, ContentType.APPLICATION_JSON); post.setEntity(entity); HttpResponse response = client.execute(post); int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { // 200 if (statsEnabled == UploadStats.No) { // If the user doesn't want to participate, he probably doesn't // want to be checking for new releases either, so disable it. pref.putBoolean(Options.OptCheckVersion, false); } // This is used to notify the user that a newer version is available HttpEntity rspEntity = response.getEntity(); if (rspEntity != null && statsEnabled != UploadStats.No) { File f = File.createTempFile("VersionPost", "html"); f.deleteOnExit(); Files.copy(rspEntity.getContent(), f.toPath(), StandardCopyOption.REPLACE_EXISTING); if (f.length() > 0) { URL rspUrl = Utilities.toURI(f).toURL(); HtmlBrowser.URLDisplayer.getDefault().showURL(rspUrl); } } } else { Log.log(Level.INFO, "CheckVersion result: {0}", status); } } catch (MalformedURLException ex) { Log.log(ex); } catch (IOException ex) { Log.log(ex); } }
From source file:fr.lissi.belilif.om2m.rest.WebServiceActions.java
/** * Do get./*w ww. j a v a 2s .com*/ * * @param uri * the uri * @param headers * the headers * @return the string * @throws Exception * the exception */ public static String doGet(URI uri, HashMap<String, String> headers) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); String respString = null; try { /* * HttpClient provides URIBuilder utility class to simplify creation and modification of request URIs. * * URI uri = new URIBuilder() .setScheme("http") .setHost("hc.apache.org/") // .setPath("/search") // .setParameter("q", * "httpclient") // .setParameter("btnG", "Google Search") // .setParameter("aq", "f") // .setParameter("oq", "") .build(); */ HttpGet httpGet = new HttpGet(uri); for (String key : headers.keySet()) { httpGet.addHeader(key, headers.get(key)); } CloseableHttpResponse response1 = httpclient.execute(httpGet); // The underlying HTTP connection is still held by the response object // to allow the response content to be streamed directly from the network socket. // In order to ensure correct deallocation of system resources // the user MUST call CloseableHttpResponse#close() from a finally clause. // Please note that if response content is not fully consumed the underlying // connection cannot be safely re-used and will be shut down and discarded // by the connection manager. try { System.out.println(response1.getStatusLine()); HttpEntity entity = response1.getEntity(); // do something useful with the response body if (entity != null) { respString = EntityUtils.toString(entity); } // and ensure it is fully consumed EntityUtils.consume(entity); } finally { response1.close(); } } finally { httpclient.close(); } return respString; }
From source file:com.oakhole.voa.utils.HttpClientUtils.java
/** * post// www. j a va 2 s.co m * * @param uri * @param map * @return */ public static String post(String uri, Map<String, Object> map) { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(uri); HttpEntity httpEntity = null; MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); for (String key : map.keySet()) { Object value = map.get(key); if (value != null && value instanceof String) { String param = (String) value; multipartEntityBuilder.addTextBody(key, param, ContentType.create("text/plain", CHARSET)); } if (value != null && value instanceof File) { multipartEntityBuilder.addBinaryBody(key, (File) value); } } try { httpPost.setEntity(multipartEntityBuilder.build()); HttpResponse httpResponse = httpClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { httpEntity = httpResponse.getEntity(); } } catch (IOException e) { logger.error(":{}", e.getMessage()); } try { return EntityUtils.toString(httpEntity, CHARSET); } catch (IOException e) { logger.error(":{}", e.getMessage()); } return ""; }
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 {// w w w . j a v a 2 s . c o m 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(); } } }