Search in sources :

Example 21 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");
    logger.debug("url=" + url);
    logger.debug("data=" + data);
    logger.debug("contentType=" + contentType);
    logger.debug("username=" + username);
    logger.debug("password=" + 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 " + responseCode);
        return response;
    } catch (IOException e) {
        logger.error("Error executing HTTP request.", 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)

Example 22 with HttpRequestBase

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

the class ClutchAPIClient method sendRequest.

private static void sendRequest(String url, boolean post, JSONObject payload, String version, final ClutchAPIResponseHandler responseHandler) {
    BasicHeader[] headers = { new BasicHeader("X-App-Version", version), new BasicHeader("X-UDID", ClutchUtils.getUDID()), new BasicHeader("X-API-Version", VERSION), new BasicHeader("X-App-Key", appKey), new BasicHeader("X-Bundle-Version", versionName), new BasicHeader("X-Platform", "Android") };
    StringEntity entity = null;
    try {
        entity = new StringEntity(payload.toString());
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, "Could not encode the JSON payload and attach it to the request: " + payload.toString());
        return;
    }
    HttpRequestBase request = null;
    if (post) {
        request = new HttpPost(url);
        ((HttpEntityEnclosingRequestBase) request).setEntity(entity);
        request.setHeaders(headers);
    } else {
        request = new HttpGet(url);
    }
    class StatusCodeAndResponse {

        public int statusCode;

        public String response;

        public StatusCodeAndResponse(int statusCode, String response) {
            this.statusCode = statusCode;
            this.response = response;
        }
    }
    new AsyncTask<HttpRequestBase, Void, StatusCodeAndResponse>() {

        @Override
        protected StatusCodeAndResponse doInBackground(HttpRequestBase... requests) {
            try {
                HttpResponse resp = client.execute(requests[0]);
                HttpEntity entity = resp.getEntity();
                InputStream inputStream = entity.getContent();
                ByteArrayOutputStream content = new ByteArrayOutputStream();
                int readBytes = 0;
                byte[] sBuffer = new byte[512];
                while ((readBytes = inputStream.read(sBuffer)) != -1) {
                    content.write(sBuffer, 0, readBytes);
                }
                inputStream.close();
                String response = new String(content.toByteArray());
                content.close();
                return new StatusCodeAndResponse(resp.getStatusLine().getStatusCode(), response);
            } catch (IOException e) {
                if (responseHandler instanceof ClutchAPIDownloadResponseHandler) {
                    ((ClutchAPIDownloadResponseHandler) responseHandler).onFailure(e, "");
                } else {
                    responseHandler.onFailure(e, null);
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(StatusCodeAndResponse resp) {
            if (responseHandler instanceof ClutchAPIDownloadResponseHandler) {
                if (resp.statusCode == 200) {
                    ((ClutchAPIDownloadResponseHandler) responseHandler).onSuccess(resp.response);
                } else {
                    ((ClutchAPIDownloadResponseHandler) responseHandler).onFailure(null, resp.response);
                }
            } else {
                if (resp.statusCode == 200) {
                    responseHandler.handleSuccessMessage(resp.response);
                } else {
                    responseHandler.handleFailureMessage(null, resp.response);
                }
            }
        }
    }.execute(request);
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) HttpEntity(org.apache.http.HttpEntity) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HttpResponse(org.apache.http.HttpResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) StringEntity(org.apache.http.entity.StringEntity) BasicHeader(org.apache.http.message.BasicHeader)

Example 23 with HttpRequestBase

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

the class AbstractProxyResponseHandler method prepareRemoteRequest.

private HttpRequestBase prepareRemoteRequest(final FullHttpRequest request, final URL url) {
    HttpRequestBase remoteRequest = createRemoteRequest(request, url);
    RequestConfig config = RequestConfig.custom().setRedirectsEnabled(false).build();
    remoteRequest.setConfig(config);
    remoteRequest.setProtocolVersion(createVersion(request));
    long contentLength = HttpUtil.getContentLength(request, -1);
    if (contentLength > 0 && remoteRequest instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) remoteRequest;
        entityRequest.setEntity(createEntity(request.content(), contentLength));
    }
    return remoteRequest;
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest)

Example 24 with HttpRequestBase

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

the class MocoRequestAction method doExecute.

private void doExecute(final CloseableHttpClient client, final Request request) throws IOException {
    HttpRequestBase targetRequest = createRequest(url, method, request);
    if (targetRequest instanceof HttpEntityEnclosingRequest && content.isPresent()) {
        ((HttpEntityEnclosingRequest) targetRequest).setEntity(asEntity(content.get(), request));
    }
    client.execute(targetRequest);
}
Also used : HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest)

Example 25 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)

Aggregations

HttpRequestBase (org.apache.http.client.methods.HttpRequestBase)49 HttpResponse (org.apache.http.HttpResponse)24 HttpGet (org.apache.http.client.methods.HttpGet)15 IOException (java.io.IOException)11 Header (org.apache.http.Header)11 HttpPost (org.apache.http.client.methods.HttpPost)10 HttpEntity (org.apache.http.HttpEntity)9 URI (java.net.URI)7 ArrayList (java.util.ArrayList)6 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)6 HttpHead (org.apache.http.client.methods.HttpHead)6 Test (org.junit.Test)6 HttpEntityEnclosingRequestBase (org.apache.http.client.methods.HttpEntityEnclosingRequestBase)5 StringEntity (org.apache.http.entity.StringEntity)5 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)5 SimpleStringExtractorHandler (com.newsrob.util.SimpleStringExtractorHandler)4 Timing (com.newsrob.util.Timing)4 InputStream (java.io.InputStream)4 URISyntaxException (java.net.URISyntaxException)4 HttpPut (org.apache.http.client.methods.HttpPut)4