Search in sources :

Example 51 with HttpRequestBase

use of org.apache.http.client.methods.HttpRequestBase in project engine by craftercms.

the class HttpProxyImpl method proxyRequest.

protected void proxyRequest(String url, boolean isGet, HttpServletRequest request, HttpServletResponse response) throws HttpProxyException {
    String targetUrl = createTargetUrl(url, request);
    HttpRequestBase httpRequest = null;
    CloseableHttpResponse httpResponse = null;
    try {
        if (isGet) {
            httpRequest = createGetRequest(targetUrl, request);
        } else {
            httpRequest = createPostRequest(targetUrl, request);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Proxying to " + getRequestDescription(httpRequest));
        }
        httpResponse = httpClient.execute(httpRequest);
        response.setStatus(httpResponse.getStatusLine().getStatusCode());
        String responseBody = IOUtils.toString(httpResponse.getEntity().getContent());
        if (httpResponse.getStatusLine().getStatusCode() >= 400 && logger.isDebugEnabled()) {
            logger.debug("Received error response from " + getRequestDescription(httpRequest) + ": status = " + httpResponse.getStatusLine().getReasonPhrase() + ", response body = \n" + responseBody);
        }
        copyActualResponseHeaders(httpRequest, response);
        copyActualResponseBody(responseBody, response);
    } catch (Exception e) {
        String errorMsg;
        if (httpRequest != null) {
            errorMsg = "Error while proxying to " + getRequestDescription(httpRequest);
        } else {
            errorMsg = "Error while proxing to " + (isGet ? "GET[" : "POST[") + targetUrl + "]";
        }
        logger.error(errorMsg, e);
        throw new HttpProxyException(errorMsg, e);
    } finally {
        if (httpRequest != null) {
            httpRequest.releaseConnection();
        }
    }
}
Also used : HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpProxyException(org.craftercms.engine.exception.HttpProxyException) IOException(java.io.IOException) HttpProxyException(org.craftercms.engine.exception.HttpProxyException)

Example 52 with HttpRequestBase

use of org.apache.http.client.methods.HttpRequestBase in project gocd by gocd.

the class ServerBinaryDownloader method fetchUpdateCheckHeaders.

void fetchUpdateCheckHeaders(DownloadableFile downloadableFile) throws Exception {
    String url = downloadableFile.validatedUrl(urlGenerator);
    final HttpRequestBase request = new HttpHead(url);
    request.setConfig(RequestConfig.custom().setConnectTimeout(HTTP_TIMEOUT_IN_MILLISECONDS).build());
    try (CloseableHttpClient httpClient = httpClientBuilder.build();
        CloseableHttpResponse response = httpClient.execute(request)) {
        handleInvalidResponse(response, url);
        this.md5 = response.getFirstHeader(MD5_HEADER).getValue();
        this.sslPort = response.getFirstHeader(SSL_PORT_HEADER).getValue();
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpHead(org.apache.http.client.methods.HttpHead)

Example 53 with HttpRequestBase

use of org.apache.http.client.methods.HttpRequestBase in project gocd by gocd.

the class TokenRequester method getToken.

public String getToken() throws IOException, InterruptedException {
    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();
    }
}
Also used : HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse)

Example 54 with HttpRequestBase

use of org.apache.http.client.methods.HttpRequestBase in project gocd by gocd.

the class TokenRequesterTest method shouldErrorOutIfServerRejectTheRequest.

@Test
public void shouldErrorOutIfServerRejectTheRequest() throws Exception {
    final ArgumentCaptor<HttpRequestBase> argumentCaptor = ArgumentCaptor.forClass(HttpRequestBase.class);
    final CloseableHttpResponse httpResponse = mock(CloseableHttpResponse.class);
    when(agentRegistry.uuid()).thenReturn("agent-uuid");
    when(httpClient.execute(any(HttpRequestBase.class))).thenReturn(httpResponse);
    when(httpResponse.getEntity()).thenReturn(new StringEntity("A token has already been issued for this agent."));
    when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("https", 1, 2), SC_UNPROCESSABLE_ENTITY, null));
    thrown.expect(RuntimeException.class);
    thrown.expectMessage("A token has already been issued for this agent.");
    tokenRequester.getToken();
}
Also used : StringEntity(org.apache.http.entity.StringEntity) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ProtocolVersion(org.apache.http.ProtocolVersion) BasicStatusLine(org.apache.http.message.BasicStatusLine) Test(org.junit.Test)

Example 55 with HttpRequestBase

use of org.apache.http.client.methods.HttpRequestBase in project SmartApplianceEnabler by camueller.

the class HttpTransactionExecutor method sendHttpRequest.

/**
 * Send a HTTP request whose response has to be closed by the caller!
 * @param url
 * @return
 */
protected CloseableHttpResponse sendHttpRequest(String url, String data, ContentType contentType, String username, String password) {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    if (username != null && password != null) {
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
        provider.setCredentials(AuthScope.ANY, credentials);
        httpClientBuilder.setDefaultCredentialsProvider(provider);
    }
    CloseableHttpClient client = httpClientBuilder.build();
    logger.debug("{}: Sending HTTP request", applianceId);
    logger.debug("{}: url={}", applianceId, url);
    logger.debug("{}: data={}", applianceId, data);
    logger.debug("{}: contentType={}", applianceId, contentType);
    logger.debug("{}: username={}", applianceId, username);
    logger.debug("{}: password={}", applianceId, password);
    try {
        HttpRequestBase request = null;
        if (data != null) {
            request = new HttpPost(url);
            ((HttpPost) request).setEntity(new StringEntity(data, contentType));
        } else {
            request = new HttpGet(url);
        }
        CloseableHttpResponse response = client.execute(request);
        int responseCode = response.getStatusLine().getStatusCode();
        logger.debug("{}: Response code is {}", applianceId, responseCode);
        return response;
    } catch (IOException e) {
        logger.error("{}: Error executing HTTP request.", applianceId, e);
        return null;
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) IOException(java.io.IOException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Aggregations

HttpRequestBase (org.apache.http.client.methods.HttpRequestBase)63 HttpResponse (org.apache.http.HttpResponse)28 HttpGet (org.apache.http.client.methods.HttpGet)20 IOException (java.io.IOException)18 Header (org.apache.http.Header)13 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)13 HttpPost (org.apache.http.client.methods.HttpPost)13 HttpEntity (org.apache.http.HttpEntity)10 StringEntity (org.apache.http.entity.StringEntity)10 URI (java.net.URI)9 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)9 Test (org.junit.Test)9 InputStream (java.io.InputStream)7 URISyntaxException (java.net.URISyntaxException)7 ArrayList (java.util.ArrayList)7 HttpHead (org.apache.http.client.methods.HttpHead)7 HttpPut (org.apache.http.client.methods.HttpPut)6 HttpEntityEnclosingRequest (org.apache.http.HttpEntityEnclosingRequest)5 HttpEntityEnclosingRequestBase (org.apache.http.client.methods.HttpEntityEnclosingRequestBase)5 HashMap (java.util.HashMap)4