Example usage for org.apache.http.client.methods CloseableHttpResponse close

List of usage examples for org.apache.http.client.methods CloseableHttpResponse close

Introduction

In this page you can find the example usage for org.apache.http.client.methods CloseableHttpResponse close.

Prototype

public void close() throws IOException;

Source Link

Document

Closes this stream and releases any system resources associated with it.

Usage

From source file:org.sonatype.nexus.internal.httpclient.HttpClientManagerImplIT.java

private void testPrepareHttpClientBuilderHttpRequest(boolean isSSL, boolean isProxy) throws Exception {
    // Setup//  w  ww .j  a  va 2  s . c om
    HttpClientBuilder builder = underTest.prepare(plan -> plan.setUserAgentBase(EXPECTED_USER_AGENT));
    builder.setConnectionManager(null);
    if (isProxy) {
        builder.setProxy(new HttpHost(proxyServer.getHostName(), proxyServer.getPort()));
    }
    if (isSSL) {
        setSSL(builder);
    }

    String url;
    if (isSSL) {
        url = "https://" + targetServerSSL.getUrl().getHost() + ":" + targetServerSSL.getPort();
    } else {
        url = "http://" + targetServer.getUrl().getHost() + ":" + targetServer.getPort();
    }

    CloseableHttpResponse resp = null;
    // Execute
    try (CloseableHttpClient client = builder.build()) {
        resp = client.execute(new HttpGet(new URI(url)));
    } finally {
        if (resp != null) {
            resp.close();
        }
    }

    // Verify
    assertThat(resp.getStatusLine().getStatusCode(), equalTo(HttpStatus.OK));
    if (isSSL) {
        assertThat(httpsValidatingBehaviour.getSuccessCount(), equalTo(1));
    } else {
        assertThat(httpValidatingBehaviour.getSuccessCount(), equalTo(1));
    }
    if (isProxy) {
        if (isSSL) {
            // Only one filterable request in SSL (CONNECT) without using MITM
            assertThat(proxyServer.getSuccessCount(), equalTo(1));
        } else {
            // Two filterable requests in non-SSL (initiate and real request)
            assertThat(proxyServer.getSuccessCount(), equalTo(2));
        }
    }
}

From source file:org.wso2.carbon.ml.analysis.test.CreateAnalysesTestCase.java

/**
 * Test creating an analysis./*from www  . ja v a  2 s. c om*/
 * 
 * @throws MLHttpClientException 
 * @throws IOException 
 */
@Test(priority = 1, description = "Create an analysis")
public void testCreateAnalysis() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient.createAnalysis(MLIntegrationTestConstants.ANALYSIS_NAME,
            mlHttpclient.getProjectId(MLIntegrationTestConstants.PROJECT_NAME_DIABETES));
    assertEquals("Unexpected response received", Response.Status.OK.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

From source file:org.activiti.rest.content.service.api.BaseSpringContentRestTestCase.java

protected void closeHttpConnections() {
    for (CloseableHttpResponse response : httpResponses) {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                log.error("Could not close http connection", e);
            }/* w w w. ja va2  s.co  m*/
        }
    }
    httpResponses.clear();
}

From source file:cn.org.once.cstack.maven.plugin.utils.RestUtils.java

/**
 * @param url/*w w  w.j  av a2s .  c om*/
 * @param parameters
 * @return
 * @throws MojoExecutionException
 * @throws CheckException
 */
public Map<String, Object> sendPostCommand(String url, Map<String, String> parameters, Log log)
        throws CheckException {
    Map<String, Object> response = new HashMap<String, Object>();
    CloseableHttpClient httpclient = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost(url);
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");

    try {
        ObjectMapper mapper = new ObjectMapper();
        StringEntity entity = new StringEntity(mapper.writeValueAsString(parameters));
        httpPost.setEntity(entity);
        CloseableHttpResponse httpResponse = httpclient.execute(httpPost, localContext);
        ResponseHandler<String> handler = new ResponseErrorHandler();
        String body = handler.handleResponse(httpResponse);
        response.put("body", body);
        httpResponse.close();
    } catch (Exception e) {
        log.warn("POST request failed!");

        throw new CheckException("Send POST to server failed!", e);
    }

    return response;
}

From source file:org.wso2.carbon.ml.project.test.MLProjectsTestCase.java

/**
 * //from  w w w. jav  a  2  s.  co  m
 * @throws MLHttpClientException
 * @throws IOException
 */
@Test(priority = 6, description = "Retrieve a non-existing project")
public void testGetNonExistingProject() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient.doHttpGet("/api/projects/" + "NON_EXISTING_PROJECT");
    assertEquals("Unexpected response received", Response.Status.NOT_FOUND.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

From source file:cn.org.once.cstack.maven.plugin.utils.RestUtils.java

/**
 * @param url//ww  w.  j a va  2s.  c  o  m
 * @param parameters
 * @param log
 * @return
 * @throws MojoExecutionException
 */
public Map<String, String> connect(String url, Map<String, Object> parameters, Log log)
        throws MojoExecutionException {

    Map<String, String> response = new HashMap<String, String>();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    List<NameValuePair> nvps = new ArrayList<>();
    nvps.add(new BasicNameValuePair("j_username", (String) parameters.get("login")));
    nvps.add(new BasicNameValuePair("j_password", (String) parameters.get("password")));
    localContext = HttpClientContext.create();
    localContext.setCookieStore(new BasicCookieStore());
    HttpPost httpPost = new HttpPost(url);

    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        CloseableHttpResponse httpResponse = httpclient.execute(httpPost, localContext);
        ResponseHandler<String> handler = new ResponseErrorHandler();
        String body = handler.handleResponse(httpResponse);
        response.put("body", body);
        httpResponse.close();
        isConnected = true;
        log.info("Connection successful");
    } catch (Exception e) {
        log.error("Connection failed!  : " + e.getMessage());
        isConnected = false;
        throw new MojoExecutionException(
                "Connection failed, please check your manager location or your credentials");
    }

    return response;
}

From source file:org.wso2.identity.sample.webapp.APIInvoker.java

private String callRESTep(String ep) throws Exception {

    PlatformUtils.setKeyStoreProperties();
    PlatformUtils.setKeyStoreParams();//from ww  w . j  ava 2 s  . c o  m

    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {
        SSLSocketFactory sf = null;
        SSLContext sslContext = null;
        StringWriter writer;
        try {
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, null, null);
        } catch (NoSuchAlgorithmException e) {
            //<YourErrorHandling>
        } catch (KeyManagementException e) {
            //<YourErrorHandling>
        }

        try {
            sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        } catch (Exception e) {
            //<YourErrorHandling>
        }
        Scheme scheme = new Scheme("https", 8243, sf);
        httpClient.getConnectionManager().getSchemeRegistry().register(scheme);
        HttpGet get = new HttpGet(ep);

        // add header
        get.setHeader("Content-Type", "text/xml;charset=UTF-8");
        get.setHeader("Authorization", "Bearer " + oauthToken);
        get.setHeader("x-saml-assertion", SamlConsumerManager.getEncodedAssertion());

        CloseableHttpResponse response = httpClient.execute(get);
        try {
            String result = EntityUtils.toString(response.getEntity());
            System.out.println("API RESULT" + result);
            return result;
        } finally {
            response.close();
        }

    } finally {
        httpClient.close();
    }
}

From source file:org.wso2.carbon.ml.analysis.test.CreateAnalysesTestCase.java

/**
 * Test creating an existing analysis.//  www  .j  a va  2s. co  m
 * 
 * @throws MLHttpClientException 
 * @throws IOException 
 */
@Test(priority = 2, description = "Create an existing analysis")
public void testCreateExistingAnalysis() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient.createAnalysis(MLIntegrationTestConstants.ANALYSIS_NAME,
            mlHttpclient.getProjectId(MLIntegrationTestConstants.PROJECT_NAME_DIABETES));
    assertEquals("Unexpected response received", Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

From source file:org.wso2.carbon.ml.project.test.MLProjectsTestCase.java

/**
 * Test creating a project without the dataset name.
 * /*from w  ww  . j ava  2  s. com*/
 * @throws MLHttpClientException
 * @throws IOException
 */
@Test(priority = 2, description = "Create a project without a dataset")
public void testCreateProjectWithoutDataset() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient.createProject("TestProjectForCreatProjectTestCase-2", null);
    assertEquals("Unexpected response received", Response.Status.BAD_REQUEST.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

From source file:com.kingja.springmvc.util.HttpRequestUtils.java

public String get(String path) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//  w w w. j a va  2  s .c  o m
        // httpget.    
        HttpGet httpget = new HttpGet(path);
        // get.    
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            // ??    
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                return EntityUtils.toString(entity);
            }
        } finally {
            response.close();
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // ,?    
        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return "";
}