Example usage for org.apache.http.impl.client CloseableHttpClient close

List of usage examples for org.apache.http.impl.client CloseableHttpClient close

Introduction

In this page you can find the example usage for org.apache.http.impl.client CloseableHttpClient 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.skfiy.typhon.rnsd.service.impl.RechargingServiceImpl.java

private void sendToGameServer(Recharging recharging) {
    Region region = regionService.load(Integer.parseInt(recharging.getRegion()));

    CloseableHttpClient hc = HC_BUILDER.build();
    HttpHost httpHost = new HttpHost(region.getIp(), region.getJmxPort());

    StringBuilder query = new StringBuilder();
    query.append(//from w w  w  . j  a v a 2s . com
            "/InvokeAction//org.skfiy.typhon.spi%3Aname%3DGMConsoleProvider%2Ctype%3Dorg.skfiy.typhon.spi.GMConsoleProvider/action=recharge?action=recharge");
    query.append("&rid%2Bjava.lang.String=").append(recharging.getUid());
    query.append("&cash%2Bjava.lang.String=").append(recharging.getGoods());

    HttpGet httpGet = new HttpGet(query.toString());
    httpGet.addHeader("Authorization", basicAuth);

    CloseableHttpResponse response = null;
    try {
        response = hc.execute(httpHost, httpGet);
    } catch (IOException ex) {
        LOG.error("host:port -> {}:{}", region.getIp(), region.getJmxPort(), ex);
        throw new RechargingException("send to game server error error", ex);
    } finally {
        try {
            hc.close();
        } catch (IOException ex) {
        }
    }

    if (response == null || response.getStatusLine().getStatusCode() != HttpStatus.OK.value()) {
        LOG.error("recharging failed. {}", response);
        throw new RechargingException("recharging failed");
    }
}

From source file:com.vmware.bdd.plugin.clouderamgr.poller.host.HostInstallPoller.java

private void login() throws Exception {
    cookieStore = new BasicCookieStore();
    CloseableHttpClient loginClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    URI uri = new URI(domain + POST_ADDR);
    HttpUriRequest login = RequestBuilder.post().setUri(uri).addParameter(POST_USER_KEY, username)
            .addParameter(POST_PASSWORD_KEY, password).build();
    logger.info("Login " + uri.toString());

    CloseableHttpResponse response = loginClient.execute(login);
    try {/*from w ww  . j a  va2  s . co  m*/
        HttpEntity entity = response.getEntity();

        logger.info("Login form get: " + response.getStatusLine());
        EntityUtils.consume(entity);

        List<Cookie> cookies = cookieStore.getCookies();
        if (cookies.isEmpty()) {
            logger.info("Get no cookies");
        } else {
            logger.info("All cookies: " + (new Gson()).toJson(cookies));
        }
    } finally {
        response.close();
        loginClient.close();
    }
}

From source file:com.conwet.wirecloud.ide.WirecloudAPI.java

public void getOAuthEndpoints() throws IOException, UnexpectedResponseException {
    URL url;/*from w  ww  .  j  a  v  a2  s.  c  o m*/
    try {
        url = new URL(this.url, OAUTH_INFO_ENDPOINT);
    } catch (MalformedURLException e) {
        throw new AssertionError(e);
    }
    HttpGet request = new HttpGet(url.toString());

    CloseableHttpClient httpclient = null;
    CloseableHttpResponse response = null;
    try {
        httpclient = createHttpClient(url);
        response = httpclient.execute(request);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new UnexpectedResponseException();
        }

        try {
            JSONObject responseData = new JSONObject(EntityUtils.toString(response.getEntity()));
            this.AUTH_ENDPOINT = responseData.getString("auth_endpoint");
            this.TOKEN_ENDPOINT = responseData.getString("token_endpoint");
            this.UNIVERSAL_REDIRECT_URI = responseData.getString("default_redirect_uri");
        } catch (JSONException e) {
            throw new UnexpectedResponseException();
        }
    } finally {
        httpclient.close();
        if (response != null) {
            response.close();
        }
    }
}

From source file:org.cleverbus.core.common.directcall.DirectCallHttpImpl.java

@Override
public String makeCall(String callId) throws IOException {
    Assert.hasText(callId, "callId must not be empty");

    CloseableHttpClient httpClient = HttpClients.createDefault();

    try {//from   w  w w  . ja v a2s  . co  m
        HttpGet httpGet = new HttpGet(localhostUri + RouteConstants.HTTP_URI_PREFIX
                + DirectCallWsRoute.SERVLET_URL + "?" + DirectCallWsRoute.CALL_ID_HEADER + "=" + callId);

        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    // successful response
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new IOException(EntityUtils.toString(response.getEntity()));
                }
            }
        };

        return httpClient.execute(httpGet, responseHandler);
    } finally {
        httpClient.close();
    }
}

From source file:org.sonar.runner.Main.java

private void doRequest(HttpPost httpRequest) throws Exception {
    CloseableHttpClient httpClient = null;
    InputStream content = null;//  w ww  .j  a v  a 2 s  .  c  o m
    StringWriter writer = null;
    try {
        httpClient = httpClientBuilder.build();
        CloseableHttpResponse response = httpClient.execute(httpRequest);
        int code = response.getStatusLine().getStatusCode();
        writer = new StringWriter();
        content = response.getEntity().getContent();
        if (content != null) {
            IOUtils.copy(response.getEntity().getContent(), writer);
        }

        if (String.valueOf(code).startsWith("20")) {
            Logs.info("success url:" + httpRequest.getURI().toString());
        } else {
            throw new Exception("Http error code:" + String.valueOf(code) + " content:" + writer.toString());
        }
    } finally {
        try {
            if (httpClient != null) {
                httpClient.close();
            }
        } catch (Exception e) {
        }
        try {
            if (content != null) {
                httpClient.close();
            }
        } catch (Exception e) {
        }
        try {
            if (writer != null) {
                httpClient.close();
            }
        } catch (Exception e) {
        }
    }
}

From source file:com.code42.demo.RestInvoker.java

/**
 * Builds and executes HttpGet Request by appending the urlQuery parameter to the 
 * serverHost:serverPort variables.  Returns the data payload response as a JSONObject. 
 * //ww  w  .java 2 s.  com
 * @param urlQuery
 * @return org.json.simple.JSONObject
 * @throws Exception
 */
public JSONObject getAPI(String urlQuery) throws Exception {
    HttpClientBuilder hcs;
    CloseableHttpClient httpClient;
    hcs = HttpClients.custom().setDefaultCredentialsProvider(credsProvider);
    if (ssl) {
        hcs.setSSLSocketFactory(sslsf);
    }
    httpClient = hcs.build();
    JSONObject data;
    try {
        HttpGet httpGet = new HttpGet(ePoint + urlQuery);
        m_log.info("Executing request: " + httpGet.getRequestLine());
        CloseableHttpResponse resp = httpClient.execute(httpGet);
        try {
            m_log.info("Respone: " + resp.getStatusLine());
            String jsonResponse = EntityUtils.toString(resp.getEntity()); // json response
            JSONParser jp = new JSONParser();
            JSONObject jObj = (JSONObject) jp.parse(jsonResponse);
            data = (JSONObject) jObj.get("data");
            m_log.debug(data);
        } finally {
            resp.close();
        }
    } finally {
        httpClient.close();
    }
    return data;
}

From source file:myexamples.dbase.MyHelpMethods.java

public static String sendHttpRequest2(String url, String requestBody, String requestType) throws IOException {
    String result = null;/*from   w  w w.j  a v  a  2s  .co  m*/
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse httpResponse;
    try {
        switch (requestType) {
        case "Get":
            httpResponse = httpclient.execute(new HttpGet(url));
            break;
        case "Post":
            HttpPost httppost = new HttpPost(url);
            if (requestBody != null)
                httppost.setEntity(new StringEntity(requestBody));
            httpResponse = httpclient.execute(httppost);
            break;
        case "Put":
            HttpPut httpPut = new HttpPut(url);
            httpPut.addHeader("Content-Type", "application/json");
            httpPut.addHeader("Accept", "application/json");
            if (requestBody != null)
                httpPut.setEntity(new StringEntity(requestBody, DEFAULT_CHARSET));
            httpResponse = httpclient.execute(httpPut);
            break;
        case "Delete":
            httpResponse = httpclient.execute(new HttpDelete(url));
            break;
        default:
            httpResponse = httpclient.execute(new HttpGet(url));
            break;
        }
        try {
            HttpEntity entity1 = httpResponse.getEntity();
            if (entity1 != null) {
                long len = entity1.getContentLength();
                if (len != -1 && len < MAX_CONTENT_LENGTH) {
                    result = EntityUtils.toString(entity1, DEFAULT_CHARSET);
                } else {
                    System.out.println("Error!!!! entity length=" + len);
                }
            }
            EntityUtils.consume(entity1);
        } finally {
            httpResponse.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        httpclient.close();
    }
    return result;
}

From source file:de.bytefish.fcmjava.client.http.HttpClient.java

private <TRequestMessage> void internalPost(TRequestMessage requestMessage) throws Exception {

    CloseableHttpClient client = null;
    try {/* w  w  w .j  av  a2 s  .co  m*/
        client = httpClientBuilder.build();
        // Initialize a new post Request:
        HttpPost httpPost = new HttpPost(settings.getFcmUrl());

        // Set the JSON String as data:
        httpPost.setEntity(new StringEntity(JsonUtils.getAsJsonString(requestMessage), StandardCharsets.UTF_8));

        // Execute the Request:
        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpPost);
            // Get the HttpEntity:
            HttpEntity entity = response.getEntity();

            // Let's be a good citizen and consume the HttpEntity:
            if (entity != null) {

                // Make Sure it is fully consumed:
                EntityUtils.consume(entity);
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
    } finally {
        if (client != null) {
            client.close();
        }
    }
}

From source file:org.jenkinsci.plugins.GitLabSecurityRealm.java

/**
 * This is where the user comes back to at the end of the OpenID redirect
 * ping-pong.//w w  w .ja  v a 2 s  . com
 */
public HttpResponse doFinishLogin(StaplerRequest request) throws IOException {
    String code = request.getParameter("code");

    if (StringUtils.isBlank(code)) {
        Log.info("doFinishLogin: missing code.");
        return HttpResponses.redirectToContextRoot();
    }

    HttpPost httpPost = new HttpPost(gitlabWebUri + "/oauth/token");
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair("client_id", clientID));
    parameters.add(new BasicNameValuePair("client_secret", clientSecret));
    parameters.add(new BasicNameValuePair("code", code));
    parameters.add(new BasicNameValuePair("grant_type", "authorization_code"));
    parameters.add(new BasicNameValuePair("redirect_uri", buildRedirectUrl(request)));
    httpPost.setEntity(new UrlEncodedFormEntity(parameters, StandardCharsets.UTF_8));

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpHost proxy = getProxy(httpPost);
    if (proxy != null) {
        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        httpPost.setConfig(config);
    }

    org.apache.http.HttpResponse response = httpclient.execute(httpPost);

    HttpEntity entity = response.getEntity();

    String content = EntityUtils.toString(entity);

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.close();

    String accessToken = extractToken(content);

    if (StringUtils.isNotBlank(accessToken)) {
        // only set the access token if it exists.
        GitLabAuthenticationToken auth = new GitLabAuthenticationToken(accessToken, getGitlabApiUri());
        SecurityContextHolder.getContext().setAuthentication(auth);

        GitlabUser self = auth.getMyself();
        User user = User.current();
        if (user != null) {
            user.setFullName(self.getName());
            // Set email from gitlab only if empty
            if (!user.getProperty(Mailer.UserProperty.class).hasExplicitlyConfiguredAddress()) {
                user.addProperty(new Mailer.UserProperty(auth.getMyself().getEmail()));
            }
        }
        fireAuthenticated(new GitLabOAuthUserDetails(self, auth.getAuthorities()));
    } else {
        Log.info("Gitlab did not return an access token.");
    }

    String referer = (String) request.getSession().getAttribute(REFERER_ATTRIBUTE);
    if (referer != null) {
        return HttpResponses.redirectTo(referer);
    }
    return HttpResponses.redirectToContextRoot(); // referer should be
    // always there, but be
    // defensive
}