List of usage examples for org.apache.http.impl.client CloseableHttpClient close
public void close() throws IOException;
From source file:org.jenkinsci.plugins.newrelicnotifier.api.NewRelicClientImpl.java
/** * {@inheritDoc}/*from w ww .jav a2 s. co m*/ */ @Override public boolean sendNotification(String apiKey, String applicationId, String description, String revision, String changelog, String user) throws IOException { URI url = null; try { url = new URI(API_URL + DEPLOYMENT_ENDPOINT); } catch (URISyntaxException e) { // no need to handle this } HttpPost request = new HttpPost(url); setHeaders(request, apiKey); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("deployment[application_id]", applicationId)); params.add(new BasicNameValuePair("deployment[description]", description)); params.add(new BasicNameValuePair("deployment[revision]", revision)); params.add(new BasicNameValuePair("deployment[changelog]", changelog)); params.add(new BasicNameValuePair("deployment[user]", user)); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params); request.setEntity(entity); CloseableHttpClient client = getHttpClient(url); try { CloseableHttpResponse response = client.execute(request); return HttpStatus.SC_CREATED == response.getStatusLine().getStatusCode(); } finally { client.close(); } }
From source file:com.nibss.util.Request.java
public void get(String url) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try {/*from ww w. j a v a 2s. c o m*/ HttpGet httpGet = new HttpGet(url); CloseableHttpResponse response1 = httpclient.execute(httpGet); try { HttpEntity entity1 = response1.getEntity(); EntityUtils.consume(entity1); } finally { response1.close(); } } finally { httpclient.close(); } }
From source file:org.jboss.additional.testsuite.jdkall.present.web.servlet.headers.CookieHeaderServletTestCase.java
@Test @OperateOnDeployment(DEPLOYMENT)/*from w ww .j a va 2 s.c o m*/ public void cookieHeaderTest(@ArquillianResource URL url) throws Exception { URL testURL = new URL(url.toString() + "cookieHeaderServlet"); final HttpGet request = new HttpGet(testURL.toString()); CloseableHttpClient httpClient = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; response = httpClient.execute(request); Assert.assertTrue("Wrong Set-Cookie header format.", response.getFirstHeader("Set-Cookie").getValue().contains("\"example cookie\"")); IOUtils.closeQuietly(response); httpClient.close(); }
From source file:edu.lternet.pasta.doi.EzidRegistrar.java
private void closeHttpClient(CloseableHttpClient httpClient) { try {/*www .ja v a 2 s . c o m*/ httpClient.close(); } catch (IOException e) { logger.error(e.getMessage()); e.printStackTrace(); } }
From source file:org.apache.camel.component.cxf.jaxrs.CxfRsSpringConsumerTest.java
@Test public void testMappingException() throws Exception { HttpGet get = new HttpGet( "http://localhost:" + port1 + "/CxfRsSpringConsumerTest/customerservice/customers/126"); get.addHeader("Accept", "application/json"); CloseableHttpClient httpclient = HttpClientBuilder.create().build(); try {//from w w w .j a va 2 s . com HttpResponse response = httpclient.execute(get); assertEquals("Get a wrong status code", 500, response.getStatusLine().getStatusCode()); assertEquals("Get a worng message header", "exception: Here is the exception", response.getHeaders("exception")[0].toString()); } finally { httpclient.close(); } }
From source file:com.worldsmostinterestinginfographic.util.OAuth2Utils.java
/** * Request an access token from the given token endpoint. * * The token endpoint given must contain all of the required properties necessary for the request. At a minimum, * this will include://w w w. j av a2 s . c o m * * grant_type * code * redirect_uri * client_id * * If the authorization code is valid and the request is successful, the access token value will be parsed from the * response and returned. If the request has failed for any reason, null will be returned. * * @param tokenEndpoint The full token endpoint, with required parameters for making the access token request * @return A valid access token if the request was successful; null otherwise. */ public static String requestAccessToken(String tokenEndpoint) { CloseableHttpClient httpClient = HttpClients.createDefault(); try { // Exchange authorization code for access token HttpPost httpPost = new HttpPost(tokenEndpoint); HttpResponse httpResponse = httpClient.execute(httpPost); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(httpResponse.getEntity().getContent())); String line = bufferedReader.readLine(); // Detect error message if (line.toLowerCase().contains("\"error\"")) { log.severe("Fatal exception occurred while making the access token request: " + line); return null; } // Extract access token String accessToken = line.split("&")[0].split("=")[1]; if (StringUtils.isEmpty(accessToken)) { log.severe( "Fatal exception occurred while making the access token request: Access token value in response is empty"); return null; } return accessToken; } catch (Exception e) { log.severe("Fatal exception occurred while making the access token request: " + e.getMessage()); e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { log.severe("Fatal exception occurred while closing HTTP client connection: " + e.getMessage()); e.printStackTrace(); } } return null; }
From source file:org.helm.notation2.wsadapter.MonomerWSLoader.java
/** * Loads the monomer categories using the URL configured in * {@code MonomerStoreConfiguration}.//from w ww.jav a 2 s. c om * * @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.bireme.cl.CheckUrl.java
public static int check(final String url, final boolean checkOnlyHeader) { if (url == null) { throw new NullPointerException(); }/*from w w w .j a v a 2s . c om*/ final CloseableHttpClient httpclient = HttpClients.createDefault(); int responseCode = -1; try { final HttpRequestBase httpX = checkOnlyHeader ? new HttpHead(fixUrl(url)) : new HttpGet(fixUrl(url)); //final HttpHead httpX = new HttpHead(fixUrl(url)); // Some servers return 500 //final HttpGet httpX = new HttpGet(fixUrl(url)); httpX.setConfig(CONFIG); httpX.setHeader(new BasicHeader("User-Agent", "Wget/1.16.1 (linux-gnu)")); httpX.setHeader(new BasicHeader("Accept", "*/*")); httpX.setHeader(new BasicHeader("Accept-Encoding", "identity")); httpX.setHeader(new BasicHeader("Connection", "Keep-Alive")); // Create a custom response handler final ResponseHandler<Integer> responseHandler = new ResponseHandler<Integer>() { @Override public Integer handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { return response.getStatusLine().getStatusCode(); } }; responseCode = httpclient.execute(httpX, responseHandler); } catch (Exception ex) { responseCode = getExceptionCode(ex); } finally { try { httpclient.close(); } catch (Exception ioe) { System.err.println(ioe.getMessage()); } } return (((responseCode == 403) || (responseCode == 500)) && checkOnlyHeader) ? check(url, false) : responseCode; }
From source file:org.cloudsimulator.utility.RestAPI.java
public static ResponseMessageString receiveString(final String restAPIURI, final String username, final String password, final String typeOfString, final String charset) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse httpResponse = null; ResponseMessageString responseMessageString = null; httpResponse = getRequestBasicAuth(httpClient, escapeURI(restAPIURI), username, password, typeOfString); if (httpResponse != null) { if (httpResponse.getStatusLine() != null) { if (httpResponse.getEntity() != null) { responseMessageString = new ResponseMessageString(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase(), IOUtils.toString(httpResponse.getEntity().getContent(), charset)); } else { responseMessageString = new ResponseMessageString(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase(), null); }// ww w. j av a2 s .c o m } else { if (httpResponse.getEntity() != null) { responseMessageString = new ResponseMessageString(null, null, IOUtils.toString(httpResponse.getEntity().getContent(), charset)); } } httpResponse.close(); } httpClient.close(); return responseMessageString; }