List of usage examples for org.apache.http.client.methods CloseableHttpResponse close
public void close() throws IOException;
From source file:org.wso2.carbon.ml.analysis.test.GetAnalysesTestCase.java
/** * Test retrieving an analysis by name.//from w ww .j av a 2 s . c o m * * @throws MLHttpClientException * @throws IOException */ @Test(description = "Retrieve an analysis by name") public void testGetAnalysis() throws MLHttpClientException, IOException { CloseableHttpResponse response = mlHttpclient .doHttpGet("/api/projects/" + projectId + "/analyses/" + MLIntegrationTestConstants.ANALYSIS_NAME); assertEquals("Unexpected response received", Response.Status.OK.getStatusCode(), response.getStatusLine().getStatusCode()); response.close(); }
From source file:com.olacabs.fabric.processors.httpwriter.HttpWriter.java
private void close(CloseableHttpResponse response) { if (null != response) { try {/*from w w w . java2 s . com*/ response.close(); } catch (IOException e) { log.error("Error closing http client: ", e); } } }
From source file:eionet.gdem.utils.HttpUtils.java
/** * Downloads remote file// ww w.j a va 2 s.c o m * @param url URL * @return Downloaded file * @throws DCMException If an error occurs. * @throws IOException If an error occurs. */ public static byte[] downloadRemoteFile(String url) throws DCMException, IOException { byte[] responseBody = null; CloseableHttpClient client = HttpClients.createDefault(); // Create a method instance. HttpGet method = new HttpGet(url); // Execute the method. CloseableHttpResponse response = null; try { response = client.execute(method); HttpEntity entity = response.getEntity(); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { LOGGER.error("Method failed: " + response.getStatusLine().getReasonPhrase()); throw new DCMException(BusinessConstants.EXCEPTION_SCHEMAOPEN_ERROR, response.getStatusLine().getReasonPhrase()); } // Read the response body. InputStream instream = entity.getContent(); responseBody = IOUtils.toByteArray(instream); // Deal with the response. // Use caution: ensure correct character encoding and is not binary data // System.out.println(new String(responseBody)); /*catch (HttpException e) { LOGGER.error("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); throw e;*/ } catch (IOException e) { LOGGER.error("Fatal transport error: " + e.getMessage()); e.printStackTrace(); throw e; } finally { // Release the connection. response.close(); method.releaseConnection(); client.close(); } return responseBody; }
From source file:com.sampleapp.db.CloudantDAOFactory.java
@Override public int getCount() { int count = 0; try {/*from w ww . j a v a 2s .c o m*/ HttpGet get = new HttpGet(url + "/" + database + "/_all_docs"); CloseableHttpResponse response = httpClient.execute(get); String result = EntityUtils.toString(response.getEntity()); response.close(); System.out.println(result); JSONObject obj = new JSONObject(result); count = obj.getInt("total_rows"); } catch (Exception e) { e.printStackTrace(); } return count; }
From source file:org.wso2.carbon.ml.project.test.MLProjectsTestCase.java
/** * Test retrieving all projects with analyses. * /*from w w w . j a v a 2s .co m*/ * @throws MLHttpClientException * @throws IOException */ @Test(priority = 5, description = "Retrieve all projects with analyses") public void testGetAllProjectsWithAnalyses() throws MLHttpClientException, IOException { CloseableHttpResponse response = mlHttpclient.doHttpGet("/api/projects/analyses"); assertEquals("Unexpected response received", Response.Status.OK.getStatusCode(), response.getStatusLine().getStatusCode()); response.close(); }
From source file:org.wso2.carbon.ml.project.test.MLProjectsTestCase.java
/** * Test deleting a non-existing project. * /* ww w . j a v a2 s . c o m*/ * @throws MLHttpClientException * @throws IOException */ @Test(priority = 8, description = "Delete an exsisting project") public void testDeleteNonExistingProject() throws MLHttpClientException, IOException { CloseableHttpResponse response = mlHttpclient.doHttpDelete("/api/projects/" + 999); assertEquals("Unexpected response received", Response.Status.OK.getStatusCode(), response.getStatusLine().getStatusCode()); response.close(); }
From source file:com.sampleapp.db.CloudantDAOFactory.java
@Override public void clearAll() { try {//from w w w.j a va 2 s.c o m HttpGet get = new HttpGet(url + "/" + database + "/_all_docs"); CloseableHttpResponse response = httpClient.execute(get); String result = EntityUtils.toString(response.getEntity()); response.close(); System.out.println(result); JSONObject obj = new JSONObject(result); JSONArray arr = obj.getJSONArray("rows"); for (int i = 0; i < arr.length(); i++) { String id = arr.getJSONObject(i).getString("id"); JSONObject revObj = arr.getJSONObject(i).getJSONObject("value"); String rev = revObj.getString("rev"); System.out.println("Deleting record with twitterName = " + id + " and rev = " + rev); deleteRecord(id, rev); } } catch (Exception e) { e.printStackTrace(); } System.out.println("Deleted all records"); }
From source file:org.keycloak.testsuite.oauth.LoginStatusIframeEndpointTest.java
@Test public void checkIframe() throws IOException { CookieStore cookieStore = new BasicCookieStore(); try (CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build()) { String redirectUri = URLEncoder.encode( suiteContext.getAuthServerInfo().getContextRoot() + "/auth/admin/master/console", "UTF-8"); HttpGet get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/auth?response_type=code&client_id=" + Constants.ADMIN_CONSOLE_CLIENT_ID + "&redirect_uri=" + redirectUri); CloseableHttpResponse response = client.execute(get); String s = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); response.close(); String action = ActionURIUtils.getActionURIFromPageSource(s); HttpPost post = new HttpPost(action); List<NameValuePair> params = new LinkedList<>(); params.add(new BasicNameValuePair("username", "admin")); params.add(new BasicNameValuePair("password", "admin")); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); post.setEntity(new UrlEncodedFormEntity(params)); response = client.execute(post); assertEquals("CP=\"This is not a P3P policy!\"", response.getFirstHeader("P3P").getValue()); Header setIdentityCookieHeader = null; Header setSessionCookieHeader = null; for (Header h : response.getAllHeaders()) { if (h.getName().equals("Set-Cookie")) { if (h.getValue().contains("KEYCLOAK_SESSION")) { setSessionCookieHeader = h; } else if (h.getValue().contains("KEYCLOAK_IDENTITY")) { setIdentityCookieHeader = h; }//from w w w .ja va 2 s .com } } assertNotNull(setIdentityCookieHeader); assertTrue(setIdentityCookieHeader.getValue().contains("HttpOnly")); assertNotNull(setSessionCookieHeader); assertFalse(setSessionCookieHeader.getValue().contains("HttpOnly")); response.close(); Cookie sessionCookie = null; for (Cookie cookie : cookieStore.getCookies()) { if (cookie.getName().equals("KEYCLOAK_SESSION")) { sessionCookie = cookie; break; } } assertNotNull(sessionCookie); get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html"); response = client.execute(get); assertEquals(200, response.getStatusLine().getStatusCode()); s = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); assertTrue(s.contains("function getCookie()")); assertEquals("CP=\"This is not a P3P policy!\"", response.getFirstHeader("P3P").getValue()); response.close(); get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html/init"); response = client.execute(get); assertEquals(403, response.getStatusLine().getStatusCode()); response.close(); get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html/init?" + "client_id=invalid" + "&origin=" + suiteContext.getAuthServerInfo().getContextRoot()); response = client.execute(get); assertEquals(403, response.getStatusLine().getStatusCode()); response.close(); get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html/init?" + "client_id=" + Constants.ADMIN_CONSOLE_CLIENT_ID + "&origin=http://invalid"); response = client.execute(get); assertEquals(403, response.getStatusLine().getStatusCode()); response.close(); get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html/init?" + "client_id=" + Constants.ADMIN_CONSOLE_CLIENT_ID + "&origin=" + suiteContext.getAuthServerInfo().getContextRoot()); response = client.execute(get); assertEquals(204, response.getStatusLine().getStatusCode()); response.close(); } }
From source file:org.apache.ofbiz.passport.user.GitHubAuthenticator.java
public static Map<String, Object> getUserInfo(HttpGet httpGet, String accessToken, String tokenType, Locale locale) throws AuthenticatorException { JSON userInfo = null;//w w w.ja v a 2 s . co m httpGet.setConfig(PassportUtil.StandardRequestConfig); CloseableHttpClient jsonClient = HttpClients.custom().build(); httpGet.setHeader(PassportUtil.AUTHORIZATION_HEADER, tokenType + " " + accessToken); httpGet.setHeader(PassportUtil.ACCEPT_HEADER, "application/json"); CloseableHttpResponse getResponse = null; try { getResponse = jsonClient.execute(httpGet); String responseString = new BasicResponseHandler().handleResponse(getResponse); if (getResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // Debug.logInfo("Json Response from GitHub: " + responseString, module); userInfo = JSON.from(responseString); } else { String errMsg = UtilProperties.getMessage(resource, "GetOAuth2AccessTokenError", UtilMisc.toMap("error", responseString), locale); throw new AuthenticatorException(errMsg); } } catch (ClientProtocolException e) { throw new AuthenticatorException(e.getMessage()); } catch (IOException e) { throw new AuthenticatorException(e.getMessage()); } finally { if (getResponse != null) { try { getResponse.close(); } catch (IOException e) { // do nothing } } } JSONToMap jsonMap = new JSONToMap(); Map<String, Object> userMap; try { userMap = jsonMap.convert(userInfo); } catch (ConversionException e) { throw new AuthenticatorException(e.getMessage()); } return userMap; }
From source file:webrequester.AbstractWebRequest.java
public String requestWithGet() { String s = ""; try {// w w w . ja va 2s . com CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet(buildURI()); CloseableHttpResponse response = httpclient.execute(httpget); try { HttpEntity entity = response.getEntity(); if (entity != null) { s = EntityUtils.toString(entity, "UTF-8"); } } finally { response.close(); } } catch (IOException ex) { return null; } return s; }