Example usage for org.apache.http.client.methods HttpRequestBase abort

List of usage examples for org.apache.http.client.methods HttpRequestBase abort

Introduction

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

Prototype

public void abort() 

Source Link

Usage

From source file:com.kolich.http.HttpClient4Closure.java

private final Either<HttpFailure, HttpSuccess> execute(final HttpRequestBase request,
        final HttpContext context) {
    HttpResponse response = null;//from  www  .j  a v a 2s  .c o  m
    try {
        // Before the request is "executed" give the consumer an entry
        // point into the raw request object to tweak as necessary first.
        // Usually things like "signing" the request or modifying the
        // destination host are done here.
        before(request, context);
        // Actually execute the request, get a response.
        response = clientExecute(request, context);
        // Immediately after execution, only if the request was executed.
        after(response, context);
        // Check if the response was "successful".  The definition of
        // success is arbitrary based on what's defined in the check()
        // method.  The default success check is simply checking the
        // HTTP status code and if it's less than 400 (Bad Request) then
        // it's considered "good".  If the user wants evaluate this
        // response against some custom criteria, they should override
        // this check() method.
        if (check(response, context)) {
            return Right.right(new HttpSuccess(response, context));
        } else {
            return Left.left(new HttpFailure(response, context));
        }
    } catch (Exception e) {
        // Something went wrong with the request, abort it,
        // return failure.
        request.abort();
        return Left.left(new HttpFailure(e, response, context));
    }
}

From source file:net.tirasa.wink.client.asynchttpclient.ApacheHttpAsyncClientConnectionHandler.java

private Future<HttpResponse> processRequest(ClientRequest request, HandlerContext context)
        throws IOException, KeyManagementException, NoSuchAlgorithmException {

    final CloseableHttpAsyncClient client = openConnection(request);
    // TODO: move this functionality to the base class
    NonCloseableOutputStream ncos = new NonCloseableOutputStream();

    EntityWriter entityWriter = null;/*from   w  w w . j  a  v  a 2  s.com*/
    if (request.getEntity() != null) {
        OutputStream os = adaptOutputStream(ncos, request, context.getOutputStreamAdapters());
        // cast is safe because we're on the client
        ApacheHttpClientConfig config = (ApacheHttpClientConfig) request.getAttribute(WinkConfiguration.class);
        // prepare the entity that will write our entity
        entityWriter = new EntityWriter(this, request, os, ncos, config.isChunked());
    }

    HttpRequestBase entityRequest = setupHttpRequest(request, entityWriter);

    try {
        return client.execute(entityRequest, new FutureCallback<HttpResponse>() {

            @Override
            public void completed(HttpResponse t) {
                LOG.debug("Client completed with response {}", t);
                try {
                    client.close();
                } catch (IOException e) {
                    LOG.error("While closing", e);
                }
            }

            @Override
            public void failed(Exception excptn) {
                LOG.error("Client failed with exception", excptn);
                try {
                    client.close();
                } catch (IOException e) {
                    LOG.error("While closing", e);
                }
            }

            @Override
            public void cancelled() {
                LOG.debug("Client execution cancelled");
                try {
                    client.close();
                } catch (IOException e) {
                    LOG.error("While closing", e);
                }
            }
        });
    } catch (Exception ex) {
        entityRequest.abort();
        throw new RuntimeException(ex);
    }
}

From source file:ch.iterate.openstack.swift.Client.java

private <T> T execute(final HttpRequestBase method, ResponseHandler<T> handler) throws IOException {
    try {//from  w ww. java  2  s  .co m
        method.setHeader(Constants.X_AUTH_TOKEN, authenticationResponse.getAuthToken());
        try {
            return client.execute(method, handler);
        } catch (AuthorizationException e) {
            method.abort();
            authenticationResponse = this.authenticate();
            method.reset();
            // Add new auth token retrieved
            method.setHeader(Constants.X_AUTH_TOKEN, authenticationResponse.getAuthToken());
            // Retry
            return client.execute(method, handler);
        }
    } catch (IOException e) {
        // In case of an IOException the connection will be released back to the connection manager automatically
        method.abort();
        throw e;
    } finally {
        method.reset();
    }
}

From source file:ch.iterate.openstack.swift.Client.java

private Response execute(final HttpRequestBase method) throws IOException {
    try {/*  w w w. j a v a2  s.  c o  m*/
        method.setHeader(Constants.X_AUTH_TOKEN, authenticationResponse.getAuthToken());
        try {
            return new DefaultResponseHandler().handleResponse(client.execute(method));
        } catch (AuthorizationException e) {
            method.abort();
            authenticationResponse = this.authenticate();
            method.reset();
            // Add new auth token retrieved
            method.setHeader(Constants.X_AUTH_TOKEN, authenticationResponse.getAuthToken());
            // Retry
            return new DefaultResponseHandler().handleResponse(client.execute(method));
        }
    } catch (IOException e) {
        // In case of an IOException the connection will be released back to the connection manager automatically
        method.abort();
        throw e;
    }
}

From source file:com.streamreduce.util.HTTPUtils.java

/**
 * Opens a connection to the specified URL with the supplied username and password,
 * if supplied, and then reads the contents of the URL.
 *
 * @param url             the url to open and read from
 * @param method          the method to use for the request
 * @param data            the request body as string
 * @param mediaType       the media type of the request
 * @param username        the username, if any
 * @param password        the password, if any
 * @param requestHeaders  the special request headers to send
 * @param responseHeaders save response headers
 * @return the read string from the//from www.j  a va  2 s  .  c  o  m
 * @throws InvalidCredentialsException if the connection credentials are invalid
 * @throws IOException                 if there is a problem with the request
 */
public static String openUrl(String url, String method, String data, String mediaType,
        @Nullable String username, @Nullable String password, @Nullable List<Header> requestHeaders,
        @Nullable List<Header> responseHeaders) throws InvalidCredentialsException, IOException {

    String response = null;

    /* Set the cookie policy */
    httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    /* Set the user agent */
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Constants.NODEABLE_HTTP_USER_AGENT);

    HttpContext context = new BasicHttpContext();
    HttpRequestBase httpMethod;

    if (method.equals("DELETE")) {
        httpMethod = new HttpDelete(url);
    } else if (method.equals("GET")) {
        httpMethod = new HttpGet(url);
    } else if (method.equals("POST")) {
        httpMethod = new HttpPost(url);
    } else if (method.equals("PUT")) {
        httpMethod = new HttpPut(url);
    } else {
        throw new IllegalArgumentException("The method you specified is not supported.");
    }

    // Put data into the request for POST and PUT requests
    if (method.equals("POST") || method.equals("PUT") && data != null) {
        HttpEntityEnclosingRequestBase eeMethod = (HttpEntityEnclosingRequestBase) httpMethod;

        eeMethod.setEntity(new StringEntity(data, ContentType.create(mediaType, "UTF-8")));
    }

    /* Set the username/password if any */
    if (username != null) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));
        context.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider);
    }

    /* Add request headers if need be */
    if (requestHeaders != null) {
        for (Header header : requestHeaders) {
            httpMethod.addHeader(header);
        }
    }

    LOGGER.debug("Making HTTP request as " + (username != null ? username : "anonymous") + ": " + method + " - "
            + url);

    /* Make the request and read the response */
    try {
        HttpResponse httpResponse = httpClient.execute(httpMethod);
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            response = EntityUtils.toString(entity);
        }
        int responseCode = httpResponse.getStatusLine().getStatusCode();
        if (responseCode == 401 || responseCode == 403) {
            throw new InvalidCredentialsException("The connection credentials are invalid.");
        } else if (responseCode < 200 || responseCode > 299) {
            throw new IOException(
                    "Unexpected status code of " + responseCode + " for a " + method + " request to " + url);
        }

        if (responseHeaders != null) {
            responseHeaders.addAll(Arrays.asList(httpResponse.getAllHeaders()));
        }
    } catch (IOException e) {
        httpMethod.abort();
        throw e;
    }

    return response;
}

From source file:org.cloudifysource.restclient.RestClientExecutor.java

private <T> T executeRequest(final HttpRequestBase request,
        final TypeReference<Response<T>> responseTypeReference) throws RestClientException {
    HttpResponse httpResponse = null;/*  w  w w .j  a  v a2s  .co m*/
    try {
        IOException lastException = null;
        int numOfTrials = DEFAULT_TRIALS_NUM;
        if (HttpGet.METHOD_NAME.equals(request.getMethod())) {
            numOfTrials = GET_TRIALS_NUM;
        }
        for (int i = 0; i < numOfTrials; i++) {
            try {
                httpResponse = httpClient.execute(request);
                lastException = null;
                break;
            } catch (IOException e) {
                if (logger.isLoggable(Level.FINER)) {
                    logger.finer("Execute get request to " + request.getURI() + ". try number " + (i + 1)
                            + " out of " + GET_TRIALS_NUM + ", error is " + e.getMessage());
                }
                lastException = e;
            }
        }
        if (lastException != null) {
            if (logger.isLoggable(Level.WARNING)) {
                logger.warning("Failed executing " + request.getMethod() + " request to " + request.getURI()
                        + " : " + lastException.getMessage());
            }
            throw MessagesUtils.createRestClientIOException(RestClientMessageKeys.EXECUTION_FAILURE.getName(),
                    lastException, request.getURI());
        }
        String url = request.getURI().toString();
        checkForError(httpResponse, url);
        return getResponseObject(responseTypeReference, httpResponse, url);
    } finally {
        request.abort();
    }
}

From source file:com.trickl.crawler.protocol.http.HttpProtocol.java

@Override
public ManagedContentEntity load(URI uri) throws IOException {
    HttpRequestBase httpRequest;

    if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
        HttpPost httpPost = new HttpPost(uri);

        // Add header data
        for (Map.Entry<String, String> headerDataEntry : headerData.entrySet()) {
            httpPost.setHeader(headerDataEntry.getKey(), headerDataEntry.getValue());
        }// ww w  .  j  a va  2  s .  com

        // Add post data
        String contentType = headerData.get("Content-Type");
        if (contentType == null || "application/x-www-form-urlencoded".equalsIgnoreCase(contentType)) {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            for (Map.Entry<String, Object> postDataEntry : postData.entrySet()) {
                nameValuePairs.add(
                        new BasicNameValuePair(postDataEntry.getKey(), postDataEntry.getValue().toString()));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        } else if ("application/json".equalsIgnoreCase(contentType)) {
            ObjectMapper mapper = new ObjectMapper();
            StringEntity se;
            try {
                String jsonString = mapper.writeValueAsString(postData);
                se = new StringEntity(jsonString);
                httpPost.setEntity(se);
            } catch (JsonGenerationException ex) {
                log.error("Failed to generate JSON.", ex);
            } catch (JsonMappingException ex) {
                log.error("Failed to generate JSON.", ex);
            }
        }
        httpRequest = httpPost;
    } else {
        httpRequest = new HttpGet(uri);
    }

    HttpResponse response = httpclient.execute(httpRequest);
    StatusLine statusline = response.getStatusLine();
    if (statusline.getStatusCode() >= HttpStatus.SC_BAD_REQUEST) {
        httpRequest.abort();
        throw new HttpResponseException(statusline.getStatusCode(), statusline.getReasonPhrase());
    }
    HttpEntity entity = response.getEntity();
    if (entity == null) {
        // Should _almost_ never happen with HTTP GET requests.
        throw new ClientProtocolException("Empty entity");
    }
    long maxlen = httpclient.getParams().getLongParameter(DroidsHttpClient.MAX_BODY_LENGTH, 0);
    return new HttpContentEntity(entity, maxlen);
}

From source file:com.comcast.drivethru.client.DefaultRestClient.java

@Override
public RestResponse execute(RestRequest request) throws HttpException {
    /* Build the URL String */
    String url = request.getUrl().setDefaultBaseUrl(defaultBaseUrl).build();

    /* Get our Apache RestRequest object */
    Method method = request.getMethod();
    HttpRequestBase req = method.getRequest(url);
    req.setConfig(request.getConfig());//from   w ww . j a va 2 s. c o  m

    /* Add the Body */
    byte[] payload = request.getBody();
    if (null != payload) {
        if (req instanceof HttpEntityEnclosingRequest) {
            HttpEntity entity = new ByteArrayEntity(payload);
            ((HttpEntityEnclosingRequest) req).setEntity(entity);
        } else {
            throw new HttpException("Cannot attach a body to a " + method.name() + " request");
        }
    }

    /* Add all Headers */
    for (Entry<String, String> pair : defaultHeaders.entrySet()) {
        req.addHeader(pair.getKey(), pair.getValue());
    }
    for (Entry<String, String> pair : request.getHeaders().entrySet()) {
        req.addHeader(pair.getKey(), pair.getValue());
    }

    /* If there is a security provider, sign */
    if (null != securityProvider) {
        securityProvider.sign(req);
    }

    /* Closed in the finally block */
    InputStream in = null;
    ByteArrayOutputStream baos = null;

    try {
        /* Finally, execute the thing */
        org.apache.http.HttpResponse resp = delegate.execute(req);

        /* Create our response */
        RestResponse response = new RestResponse(resp.getStatusLine());

        /* Add all Headers */
        response.addAll(resp.getAllHeaders());

        /* Add the content */
        HttpEntity body = resp.getEntity();
        if (null != body) {
            in = body.getContent();
            baos = new ByteArrayOutputStream();
            IOUtils.copy(in, baos);
            response.setBody(baos.toByteArray());
        }

        return response;
    } catch (RuntimeException ex) {
        // release resources immediately
        req.abort();
        throw ex;
    } catch (HttpResponseException hrex) {
        throw new HttpStatusException(hrex.getStatusCode());
    } catch (ClientProtocolException cpex) {
        throw new HttpException("HTTP Protocol error occurred.", cpex);
    } catch (IOException ioex) {
        throw new HttpException("Error establishing connection.", ioex);
    } finally {
        req.abort();
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(baos);
    }
}

From source file:com.wareninja.android.commonutils.foursquareV2.http.AbstractHttpApi.java

/**
 * execute() an httpRequest catching exceptions and returning null instead.
 *
 * @param httpRequest/*from ww w.j  a  v a  2s .  com*/
 * @return
 * @throws IOException
 */
public HttpResponse executeHttpRequest(HttpRequestBase httpRequest) throws IOException {
    if (DEBUG)
        Log.d(TAG,
                "executing HttpRequest for: " + httpRequest.getURI().toString() + "|" + httpRequest.getMethod()
        //+ "|" + httpRequest.getParams()
        //+ "|" + httpRequest.getAllHeaders()
        );
    /*
    // YG: just for debugging
    String headersStr = "";
    Header[] headers = httpRequest.getAllHeaders();
    for (Header header:headers) {
       headersStr += "|" + header.getName() + ":" + header.getValue();
    }
    String paramsStr = "";
    HttpParams params = httpRequest.getParams();
    paramsStr += "|fs_username=" + params.getParameter("fs_username");
    paramsStr += "|fs_password=" + params.getParameter("fs_password");
    if (DEBUG) Log.d(TAG, "HttpRequest Headers for: "
        + httpRequest.getURI().toString()
        + "|" + headersStr
        + "|" + paramsStr
        );
    */
    /*
    executing HttpRequest for: https://api.foursquare.com/v1/authexchange.json|POST
    HttpRequest Headers for: https://api.foursquare.com/v1/authexchange.json|
    |User-Agent:com.wareninja.android.mayormonster:1|Authorization:OAuth oauth_version="1.0",oauth_nonce="3568494401228",oauth_signature_method="HMAC-SHA1",oauth_consumer_key="P5BV4EIC5RC5MF1STSVPNLPRBF3M5S0OVXKRLIIN0QMU3BEA",oauth_token="",oauth_timestamp="1294862657",oauth_signature="dq7ej2ChkH8uXqLKJ2qICrcIUgk%3D"|
    |fs_username=null|fs_password=null
            
    HttpRequest Headers for: https://api.foursquare.com/v1/authexchange.json||User-Agent:com.wareninja.android.mayormonster:1|Authorization:OAuth oauth_version="1.0",oauth_nonce="3568497175618",oauth_signature_method="HMAC-SHA1",oauth_consumer_key="P5BV4EIC5RC5MF1STSVPNLPRBF3M5S0OVXKRLIIN0QMU3BEA",oauth_token="",oauth_timestamp="1294862657",oauth_signature="5BHzUcaSioV%2BdIX5HiB9C2AyuzA%3D"|
    |fs_username=null|fs_password=null
            
            
     */

    //-WareNinjaUtils.trustEveryone();//YG

    try {
        mHttpClient.getConnectionManager().closeExpiredConnections();
        return mHttpClient.execute(httpRequest);
    } catch (IOException e) {
        httpRequest.abort();
        throw e;
    }
}