org.apache.http.client.methods.HttpRequestBase#releaseConnection()源码实例Demo

下面列出了org.apache.http.client.methods.HttpRequestBase#releaseConnection() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: cloudstack   文件: BrocadeVcsApi.java
protected HttpResponse executeMethod(HttpRequestBase method) throws BrocadeVcsApiException {
    HttpResponse response = null;
    try {
        response = _client.execute(method);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            method.releaseConnection();
            response = _client.execute(method);
        }
    } catch (final IOException e) {
        s_logger.error("IOException caught while trying to connect to the Brocade Switch", e);
        method.releaseConnection();
        throw new BrocadeVcsApiException("API call to Brocade Switch Failed", e);
    }

    return response;
}
 
源代码2 项目: wc-api-java   文件: DefaultHttpClient.java
private <T> T getEntityAndReleaseConnection(HttpRequestBase httpRequest, Class<T> objectClass) {
    try {
        HttpResponse httpResponse = httpClient.execute(httpRequest);
        HttpEntity httpEntity = httpResponse.getEntity();
        if (httpEntity == null) {
            throw new RuntimeException("Error retrieving results from http request");
        }
        Object result = mapper.readValue(httpEntity.getContent(), Object.class);
        if (objectClass.isInstance(result)) {
            return objectClass.cast(result);
        }
        throw new RuntimeException("Can't parse retrieved object: " + result.toString());
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        httpRequest.releaseConnection();
    }
}
 
源代码3 项目: lucene-solr   文件: JettyWebappTest.java
public void testAdminUI() throws Exception
{
  // Currently not an extensive test, but it does fire up the JSP pages and make
  // sure they compile ok

  String adminPath = "http://127.0.0.1:"+port+context+"/";
  byte[] bytes = IOUtils.toByteArray( new URL(adminPath).openStream() );
  assertNotNull( bytes ); // real error will be an exception

  HttpClient client = HttpClients.createDefault();
  HttpRequestBase m = new HttpGet(adminPath);
  HttpResponse response = client.execute(m, HttpClientUtil.createNewHttpClientRequestContext());
  assertEquals(200, response.getStatusLine().getStatusCode());
  Header header = response.getFirstHeader("X-Frame-Options");
  assertEquals("DENY", header.getValue().toUpperCase(Locale.ROOT));
  m.releaseConnection();
}
 
源代码4 项目: spark-jobs-rest-client   文件: HttpRequestUtil.java
static <T extends SparkResponse>  T executeHttpMethodAndGetResponse(HttpClient client, HttpRequestBase httpRequest, Class<T> responseClass) throws FailedSparkRequestException {
    T response;
    try {
        final String stringResponse = client.execute(httpRequest, new BasicResponseHandler());
        if (stringResponse != null) {
            response = MapperWrapper.MAPPER.readValue(stringResponse, responseClass);
        } else {
            throw new FailedSparkRequestException("Received empty string response");
        }
    } catch (IOException e) {
        throw new FailedSparkRequestException(e);
    } finally {
        httpRequest.releaseConnection();
    }

    if (response == null) {
        throw new FailedSparkRequestException("An issue occured with the cluster's response.");
    }

    return response;
}
 
源代码5 项目: gocd   文件: TokenRequester.java
public String getToken() throws IOException {
    LOGGER.debug("[Agent Registration] Using URL {} to get a token.", tokenURL);

    HttpRequestBase getTokenRequest = (HttpRequestBase) RequestBuilder.get(tokenURL)
            .addParameter("uuid", agentRegistry.uuid())
            .build();

    try (CloseableHttpResponse response = httpClient.execute(getTokenRequest)) {
        final String responseBody = responseBody(response);
        if (response.getStatusLine().getStatusCode() == SC_OK) {
            LOGGER.info("The server has generated token for the agent.");
            return responseBody;
        } else {
            LOGGER.error("Received status code from server {}", response.getStatusLine().getStatusCode());
            LOGGER.error("Reason for failure {} ", responseBody);
            throw new RuntimeException(responseBody);
        }
    } finally {
        getTokenRequest.releaseConnection();
    }
}
 
源代码6 项目: feiqu-opensource   文件: HttpClientUtil.java
/**
 * @param encoding 字符编码
 * @return 网页内容
 */
public static String getWebPage(HttpRequestBase request
        , String encoding) throws IOException {
    CloseableHttpResponse response = null;
    response = getResponse(request);
    logger.info("status---" + response.getStatusLine().getStatusCode());
    String content = EntityUtils.toString(response.getEntity(),encoding);
    request.releaseConnection();
    return content;
}
 
源代码7 项目: kylin-on-parquet-v2   文件: RestService.java
public String execRequest(HttpRequestBase request, int connectionTimeout, int readTimeout) throws IOException {
    HttpClient httpClient = getHttpClient(connectionTimeout, readTimeout);
    try {
        HttpResponse response = httpClient.execute(request);
        String msg = EntityUtils.toString(response.getEntity());
        int code = response.getStatusLine().getStatusCode();
        if (logger.isTraceEnabled()) {
            String displayMessage;
            if (msg.length() > 500) {
                displayMessage = msg.substring(0, 500);
            } else {
                displayMessage = msg;
            }
            logger.trace("Send request: {}. And receive response[{}] which lenght is {}, and content is {}.", code,
                    request.getRequestLine(), msg.length(), displayMessage);
        }
        if (code != 200)
            throw new IOException("Invalid http response " + code + " when send request: "
                    + request.getURI().toString() + "\n" + msg);
        return msg;
    } catch (IOException e) {
        logger.error("error when send http request:" + request.getURI().toString(), e);
        throw e;
    } finally {
        request.releaseConnection();
    }
}
 
public void execute(final URI serviceEndpoint) throws Exception {
  HttpRequestBase request = null;

  try {
    String endpoint = serviceEndpoint.toASCIIString();
    String requestUrl = endpoint.substring(0, endpoint.length() - 1) + path;
    if (queryOptions != null) {
      requestUrl += queryOptions;
    }
    request = this.request.createRequest(requestUrl);

    requestLine = request.getRequestLine().toString();
    HttpClient httpClient = new DefaultHttpClient();

    LOG.debug("Execute test for [" + requestLine + "]");
    final HttpResponse response = httpClient.execute(request);
    LOG.debug("Got response for request [" + requestLine + "]");

    int resultStatusCode = response.getStatusLine().getStatusCode();
    assertEquals("Unexpected status code for " + toString(), expectedStatusCode.getStatusCode(), resultStatusCode);

    final String contentType = response.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue();
    assertEquals("Unexpected content type for " + toString(), ContentType.create(expectedContentType), ContentType.create(contentType));

    if (isContentExpected) {
      assertNotNull("Unexpected content for " + toString(), StringHelper.inputStreamToString(response.getEntity().getContent()));
    }
    LOG.trace("Test passed [" + toString() + "]");
  } finally {
    if (request != null) {
      request.releaseConnection();
      LOG.debug("Released connection [" + requestLine + "]");
    }
  }
}
 
源代码9 项目: cs-actions   文件: HttpClientService.java
private void checkKeepAlive(HttpRequestBase httpRequestBase, PoolingHttpClientConnectionManager connManager,
                            String keepAliveInput, CloseableHttpResponse httpResponse) {
    boolean keepAlive = StringUtils.isBlank(keepAliveInput) || Boolean.parseBoolean(keepAliveInput);
    if (keepAlive) {
        httpRequestBase.releaseConnection();
    } else {
        try {
            httpResponse.close();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        httpRequestBase.releaseConnection();
        connManager.closeExpiredConnections();
    }
}
 
源代码10 项目: embedded-elasticsearch   文件: HttpClient.java
<T> T execute(HttpRequestBase request, Function<CloseableHttpResponse, T> block) {
    try (CloseableHttpResponse response = internalHttpClient.execute(request)) {
        return block.apply(response);
    } catch (IOException e) {
        throw new HttpRequestException(e);
    } finally {
        request.releaseConnection();
    }
}
 
protected String executeRequest(HttpRequestBase request) throws ElasticsearchClientException
{
    Validate.notNull(httpClient, "Has the ElasticsearchClient been initialized?");
    
    try
    {
        HttpResponse response = httpClient.execute(request);

        int statusCode = response.getStatusLine().getStatusCode();
        String content = readContent(response.getEntity());
        log.debug(String.format(
                "Response with status code %d and content: %s", statusCode, content));

        // some PUT requests return 200, some 201 :-O
        if (statusCode != 200 && statusCode != 201)
        {
            throw new ElasticsearchClientException(request.getMethod(), statusCode, content);
        }

        return content;
    }
    catch (IOException e)
    {
        throw new ElasticsearchClientException(e);
    }
    finally
    {
        request.releaseConnection();
    }
}
 
源代码12 项目: kylin   文件: RestClient.java
private void cleanup(HttpRequestBase request, HttpResponse response) {
    try {
        if (response != null)
            EntityUtils.consume(response.getEntity());
    } catch (Exception ex) {
        logger.error("Error during HTTP connection cleanup", ex);
    }
    request.releaseConnection();
}
 
public void execute(final URI serviceEndpoint) throws Exception {
  HttpRequestBase request = null;

  try {
    String endpoint = serviceEndpoint.toASCIIString();
    String requestUrl = endpoint.substring(0, endpoint.length() - 1) + path;
    if (queryOptions != null) {
      requestUrl += queryOptions;
    }
    request = this.request.createRequest(requestUrl);

    requestLine = request.getRequestLine().toString();
    HttpClient httpClient = new DefaultHttpClient();

    LOG.debug("Execute test for [" + requestLine + "]");
    final HttpResponse response = httpClient.execute(request);
    LOG.debug("Got response for request [" + requestLine + "]");

    int resultStatusCode = response.getStatusLine().getStatusCode();
    assertEquals("Unexpected status code for " + toString(), expectedStatusCode.getStatusCode(), resultStatusCode);

    final String contentType = response.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue();
    assertEquals("Unexpected content type for " + toString(), ContentType.create(expectedContentType), ContentType
        .create(contentType));

    if (isContentExpected) {
      assertNotNull("Unexpected content for " + toString(), StringHelper.inputStreamToString(response.getEntity()
          .getContent()));
    }
    LOG.trace("Test passed [" + toString() + "]");
  } finally {
    if (request != null) {
      request.releaseConnection();
      LOG.debug("Released connection [" + requestLine + "]");
    }
  }
}
 
源代码14 项目: carbon-apimgt   文件: HttpRequestUtil.java
/**
 * Executes the HTTPMethod with retry.
 *
 * @param httpClient     HTTPClient
 * @param httpMethod     HTTPMethod
 * @param retryCount No of retries
 * @return response. it will return an empty string if response body is null
 * @throws OnPremiseGatewayException throws {@link OnPremiseGatewayException}
 */
public static String executeHTTPMethodWithRetry(HttpClient httpClient, HttpRequestBase httpMethod, int retryCount)
        throws OnPremiseGatewayException {

    String result = OnPremiseGatewayConstants.EMPTY_STRING;
    HttpResponse response;
    int executionCount = 0;
    String methodName = httpMethod.getMethod();
    String uri = getURI(httpMethod);

    //Add an unique identifier as a custom header for distinguishing requests from different micro gateways.
    String token = ConfigManager.getConfigurationDTO().getStatus_unique_identifier();
    if (StringUtils.isNotBlank(token) && !(OnPremiseGatewayConstants.API_REQUEST_UNIQUE_IDENTIFIER_HOLDER
            .equals(token))) {
        if (log.isDebugEnabled()) {
            log.debug("Adding unique identifier as an header to the http " + methodName + " request.");
        }
        httpMethod.addHeader(OnPremiseGatewayConstants.APT_REQUEST_TOKEN_HEADER, token);
    }
    do {
        try {
            executionCount++;
            response = httpClient.execute(httpMethod);
            if (log.isDebugEnabled()) {
                log.debug(
                        "HTTP response code for the " + methodName + " request to URL: " + uri + " is " + response);
            }
            result = handleResponse(response, methodName, true, executionCount, retryCount, uri);
            if (!OnPremiseGatewayConstants.EMPTY_STRING.equals(result)) {
                return result;
            }
        } catch (IOException e) {
            handleExceptionWithRetry(executionCount, retryCount, methodName, uri, e);
        } finally {
            httpMethod.releaseConnection();
        }
    } while (executionCount < retryCount);
    return result;
}
 
源代码15 项目: carbon-apimgt   文件: HttpRequestUtil.java
/**
 * Executes HTTPMethod without retry
 *
 * @param httpClient HTTPClient
 * @param httpMethod HTTPMethod
 * @return response. it will return an empty string if response body is null
 * @throws OnPremiseGatewayException throws {@link OnPremiseGatewayException}
 */
public static String executeHTTPMethod(HttpClient httpClient, HttpRequestBase httpMethod)
        throws OnPremiseGatewayException {

    String result;
    HttpResponse response;
    String uri = getURI(httpMethod);
    String methodName = httpMethod.getMethod();

    //Add an unique identifier as an custom header for distinguishing requests from different micro gateways.
    String token = ConfigManager.getConfigurationDTO().getStatus_unique_identifier();
    if (StringUtils.isNotBlank(token) && !(OnPremiseGatewayConstants.API_REQUEST_UNIQUE_IDENTIFIER_HOLDER
            .equals(token))) {
        if (log.isDebugEnabled()) {
            log.debug("Adding unique identifier as an header to the http " + methodName + " request.");
        }
        httpMethod.addHeader(OnPremiseGatewayConstants.APT_REQUEST_TOKEN_HEADER, token);
    }
    try {
        response = httpClient.execute(httpMethod);
        if (log.isDebugEnabled()) {
            log.debug("HTTP response code for the " + methodName + " request: " + uri + " is " + response);
        }
        result = handleResponse(response, methodName, false, 0, 0, uri);
    } catch (IOException e) {
        throw new OnPremiseGatewayException(methodName + " request failed for URI: " + uri, e);
    } finally {
        httpMethod.releaseConnection();
    }
    return result;
}
 
private void releaseConnection(HttpRequestBase request) {
    if (request != null) {
        request.releaseConnection();
    }
}
 
源代码17 项目: shimmer   文件: OAuth1Shim.java
@Override
public AuthorizationResponse processRedirect(HttpServletRequest servletRequest) throws ShimException {

    // Fetch the access token.
    String stateKey = servletRequest.getParameter("state");
    String requestToken = servletRequest.getParameter(OAuth.OAUTH_TOKEN);
    final String requestVerifier = servletRequest.getParameter(OAuth.OAUTH_VERIFIER);

    AuthorizationRequestParameters authParams = authorizationRequestParametersRepo.findByStateKey(stateKey);
    if (authParams == null) {
        throw new ShimException("Invalid state, could not find corresponding auth parameters");
    }

    // Get the token secret from the original access request.
    String requestTokenSecret = authParams.getRequestParams().get(OAuth.OAUTH_TOKEN_SECRET);

    HttpResponse response;
    HttpRequestBase accessTokenRequest = null;
    try {
        accessTokenRequest = getAccessTokenRequest(getAccessTokenUrl(),
                requestToken, requestTokenSecret, new HashMap<String, String>() {{
                    put(OAuth.OAUTH_VERIFIER, requestVerifier);
                }});
        response = httpClient.execute(accessTokenRequest);
    }
    catch (IOException e) {
        e.printStackTrace();
        throw new ShimException("Could not retrieve response from token URL");
    }
    finally {
        if (accessTokenRequest != null) {
            accessTokenRequest.releaseConnection();
        }
    }
    Map<String, String> accessTokenParameters = OAuth1Utils.parseRequestTokenResponse(response);
    String accessToken = accessTokenParameters.get(OAuth.OAUTH_TOKEN);
    String accessTokenSecret = accessTokenParameters.get(OAuth.OAUTH_TOKEN_SECRET);

    if (accessToken == null) {
        throw new ShimException("Access token could not be retrieved");
    }

    AccessParameters accessParameters = new AccessParameters();
    accessParameters.setClientId(getClientSettings().getClientId());
    accessParameters.setClientSecret(getClientSettings().getClientSecret());
    accessParameters.setStateKey(stateKey);
    accessParameters.setUsername(authParams.getUsername());
    accessParameters.setAccessToken(accessToken);
    accessParameters.setTokenSecret(accessTokenSecret);
    accessParameters.setAdditionalParameters(new HashMap<String, Object>() {{
        put(OAuth.OAUTH_VERIFIER, requestVerifier);
    }});
    loadAdditionalAccessParameters(servletRequest, accessParameters);
    return AuthorizationResponse.authorized(accessParameters);
}
 
源代码18 项目: jenkins-client-java   文件: JenkinsHttpClient.java
private void releaseConnection(HttpRequestBase httpRequestBase) {
    httpRequestBase.releaseConnection();
}
 
源代码19 项目: attic-stratos   文件: IntegrationMockClient.java
private void releaseConnection(HttpRequestBase request) {
    if (request != null) {
        request.releaseConnection();
    }
}
 
源代码20 项目: gocd   文件: SslInfrastructureService.java
protected boolean requestRegistration(String agentHostName, AgentAutoRegistrationProperties agentAutoRegisterProperties) throws IOException {
    LOGGER.debug("[Agent Registration] Using URL {} to register.", serverUrl);

    HttpRequestBase postMethod = (HttpRequestBase) RequestBuilder.post(serverUrl)
            .addParameter("hostname", agentHostName)
            .addParameter("uuid", agentRegistry.uuid())
            .addParameter("location", SystemUtil.currentWorkingDirectory())
            .addParameter("usablespace", String.valueOf(AgentRuntimeInfo.usableSpace(SystemUtil.currentWorkingDirectory())))
            .addParameter("operatingSystem", new SystemEnvironment().getOperatingSystemCompleteName())
            .addParameter("agentAutoRegisterKey", agentAutoRegisterProperties.agentAutoRegisterKey())
            .addParameter("agentAutoRegisterResources", agentAutoRegisterProperties.agentAutoRegisterResources())
            .addParameter("agentAutoRegisterEnvironments", agentAutoRegisterProperties.agentAutoRegisterEnvironments())
            .addParameter("agentAutoRegisterHostname", agentAutoRegisterProperties.agentAutoRegisterHostname())
            .addParameter("elasticAgentId", agentAutoRegisterProperties.agentAutoRegisterElasticAgentId())
            .addParameter("elasticPluginId", agentAutoRegisterProperties.agentAutoRegisterElasticPluginId())
            .addParameter("token", agentRegistry.token())
            .build();

    try (CloseableHttpResponse response = httpClient.execute(postMethod)) {
        switch (getStatusCode(response)) {
            case SC_ACCEPTED:
                LOGGER.debug("The server has accepted the registration request.");
                break;
            case SC_FORBIDDEN:
                LOGGER.debug("Server denied registration request due to invalid token. Deleting existing token from disk.");
                agentRegistry.deleteToken();
                break;
            case SC_OK:
                LOGGER.info("This agent is now approved by the server.");
                return true;
            case SC_UNPROCESSABLE_ENTITY:
                LOGGER.error("Error occurred during agent registration process: {}", responseBody(response));
                break;
            default:
                LOGGER.warn("The server sent a response that we could not understand. The HTTP status was {}. The response body was:\n{}", response.getStatusLine(), responseBody(response));
        }
    } finally {
        postMethod.releaseConnection();
    }
    return false;
}