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

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

Introduction

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

Prototype

void abort() throws UnsupportedOperationException;

Source Link

Document

Aborts execution of the request.

Usage

From source file:com.mobilesolutionworks.android.http.WorksHttpClient.java

/**
 * Execute the request on this works http client.
 *
 * @param context  application context//from  www. j av  a  2 s. c o  m
 * @param request  works http request
 * @param listener works operation listener
 * @return works http response
 */
public static <Result> WorksHttpResponse<Result> executeOperation(Context context, WorksHttpRequest request,
        final WorksHttpOperationListener listener) {
    final HttpUriRequest httpRequest;
    HttpResponse httpResponse = null;

    WorksHttpResponse<Result> response = new WorksHttpResponse<Result>();
    response.request = request;

    WorksHttpClient instance = WorksHttpClient.getInstance(context);
    AndroidHttpClient client = instance.getHttpClient();

    switch (request.method) {
    default:
    case GET: {
        Uri.Builder builder = Uri.parse(request.url).buildUpon();

        if (request.httpParams != null) {
            for (Map.Entry<String, String> entry : request.httpParams.entrySet()) {
                builder.appendQueryParameter(entry.getKey(), entry.getValue());
            }
        }

        httpRequest = new HttpGet(builder.build().toString());
        break;
    }

    case POST: {
        HttpPost httpPost = new HttpPost(request.url);
        if (request.httpParams != null) {
            List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
            for (Map.Entry<String, String> entry : request.httpParams.entrySet()) {
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }

            UrlEncodedFormEntity result;

            try {
                result = new UrlEncodedFormEntity(params, "UTF-8");
                httpPost.setEntity(result);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }

        httpRequest = httpPost;
    }
    }

    request.abortable = new WorksHttpRequest.Abortable() {
        @Override
        public void abort() {
            httpRequest.abort();
        }
    };

    if (request.preExecutor != null) {
        request.preExecutor.onPreExecute(request, httpRequest);
    }

    listener.onPreExecute(request, httpRequest);

    httpRequest.addHeader("Works-Http-Client", instance.getName());
    try {
        HttpContext httpContext = listener.getHttpContext();
        httpResponse = client.execute(httpRequest, httpContext);

        if (listener.onValidateResponse(request, httpResponse)) {
            response.statusCode = httpResponse.getStatusLine().getStatusCode();

            boolean handled = false;
            try {
                handled = listener.onHandleResponse(request, httpRequest, response, httpResponse);
            } catch (Exception e) {
                response.markErrorInHandler(e);
                handled = true;
            }

            if (!handled) {
                int contentLength = -1;
                Header[] headers = httpResponse.getHeaders("Content-Length");
                if (headers != null) {
                    for (Header header : headers) {
                        String value = header.getValue();
                        contentLength = TypeUtils.parseInt(value);
                    }
                }

                if (request.returnTransfer) {
                    InputStream content = httpResponse.getEntity().getContent();
                    response.text = IOUtils
                            .consumeAsString(new CountingInputStream(content, listener, contentLength));
                } else if (request.out != null) {
                    InputStream content = httpResponse.getEntity().getContent();
                    IOUtils.copy(new CountingInputStream(content, listener, contentLength), request.out);
                }

                response.markSuccess();
            }
        } else {
            response.markInvalidHttpStatus(httpResponse.getStatusLine().getStatusCode());
        }
    } catch (Exception e) {
        response.markErrorInExecution(e);
    } finally {
        try {
            client.close();
        } catch (Exception e) {
            // e.printStackTrace();
        }
        if (httpResponse != null) {
            try {
                httpResponse.getEntity().consumeContent();
            } catch (IOException e) {
                // e.printStackTrace();
            }
        }
    }

    return response;
}

From source file:com.siddroid.offlinews.SendOffline.java

/**
 * Fetch response./*  w  ww .  j a va 2 s .c o m*/
 * This function executes request.
 * @param request the request
 * @param client the client
 * @return the input stream
 */
private InputStream fetchResponse(HttpUriRequest request, DefaultHttpClient client) {
    try {

        Log.d("CHECK", ("executing request " + request.getRequestLine()));
        /*execute request and get response*/
        HttpResponse getResponse = client.execute(request);
        final int statusCode = getResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            Log.d(getClass().getSimpleName(), "Error " + statusCode + " for URL " + request.getURI());
            return null;
        }
        HttpEntity getResponseEntity = getResponse.getEntity();
        /*return response inputstream*/
        return getResponseEntity.getContent();
    } catch (IOException e) {
        request.abort();
    }
    return null;
}

From source file:com.nexmo.insight.sdk.NexmoInsightClient.java

public InsightResult request(final String number, final String callbackUrl, final String[] features,
        final long callbackTimeout, final String callbackMethod, final String clientRef, final String ipAddress)
        throws IOException, SAXException {
    if (number == null || callbackUrl == null)
        throw new IllegalArgumentException("number and callbackUrl parameters are mandatory.");
    if (callbackTimeout >= 0 && (callbackTimeout < 1000 || callbackTimeout > 30000))
        throw new IllegalArgumentException("callback timeout must be between 1000 and 30000.");

    log.debug("HTTP-Number-Insight Client .. to [ " + number + " ] ");

    List<NameValuePair> params = new ArrayList<>();

    params.add(new BasicNameValuePair("api_key", this.apiKey));
    params.add(new BasicNameValuePair("api_secret", this.apiSecret));

    params.add(new BasicNameValuePair("number", number));
    params.add(new BasicNameValuePair("callback", callbackUrl));

    if (features != null)
        params.add(new BasicNameValuePair("features", strJoin(features, ",")));

    if (callbackTimeout >= 0)
        params.add(new BasicNameValuePair("callback_timeout", String.valueOf(callbackTimeout)));

    if (callbackMethod != null)
        params.add(new BasicNameValuePair("callback_method", callbackMethod));

    if (ipAddress != null)
        params.add(new BasicNameValuePair("ip", ipAddress));

    if (clientRef != null)
        params.add(new BasicNameValuePair("client_ref", clientRef));

    String inshightBaseUrl = this.baseUrl + PATH_INSIGHT;

    // Now that we have generated a query string, we can instanciate a HttpClient,
    // construct a POST or GET method and execute to submit the request
    String response = null;//from w  w  w  .j av  a  2s.com
    for (int pass = 1; pass <= 2; pass++) {
        HttpPost httpPost = new HttpPost(inshightBaseUrl);
        httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        HttpUriRequest method = httpPost;
        String url = inshightBaseUrl + "?" + URLEncodedUtils.format(params, "utf-8");

        try {
            if (this.httpClient == null)
                this.httpClient = HttpClientUtils.getInstance(this.connectionTimeout, this.soTimeout)
                        .getNewHttpClient();
            HttpResponse httpResponse = this.httpClient.execute(method);
            int status = httpResponse.getStatusLine().getStatusCode();
            if (status != 200)
                throw new Exception(
                        "got a non-200 response [ " + status + " ] from Nexmo-HTTP for url [ " + url + " ] ");
            response = new BasicResponseHandler().handleResponse(httpResponse);
            log.info(".. SUBMITTED NEXMO-HTTP URL [ " + url + " ] -- response [ " + response + " ] ");
            break;
        } catch (Exception e) {
            method.abort();
            log.info("communication failure: " + e);
            String exceptionMsg = e.getMessage();
            if (exceptionMsg.indexOf("Read timed out") >= 0) {
                log.info(
                        "we're still connected, but the target did not respond in a timely manner ..  drop ...");
            } else {
                if (pass == 1) {
                    log.info("... re-establish http client ...");
                    this.httpClient = null;
                    continue;
                }
            }

            // return a COMMS failure ...
            return new InsightResult(InsightResult.STATUS_COMMS_FAILURE, null, null, 0, 0,
                    "Failed to communicate with NEXMO-HTTP url [ " + url + " ] ..." + e, true);
        }
    }

    Document doc;
    synchronized (this.documentBuilder) {
        doc = this.documentBuilder.parse(new InputSource(new StringReader(response)));
    }

    Element root = doc.getDocumentElement();
    if (!"lookup".equals(root.getNodeName()))
        throw new IOException("No valid response found [ " + response + "] ");

    return parseInsightResult(root);
}

From source file:ch.sourcepond.maven.plugin.jenkins.config.download.DownloaderImpl.java

@Override
public String downloadCliJar(final Log pLog, final Config pValidatedConfig) throws MojoExecutionException {
    try (final CloseableHttpClient client = clientFacade.newClient(pValidatedConfig)) {
        final String jenkinsVersion = determineJenkinsVersion(pLog, client, pValidatedConfig);

        final Path downloadedCliJar = getDownloadedCliJar(pValidatedConfig.getJenkinscliDirectory(),
                jenkinsVersion);//from  ww w. jav  a 2 s. co  m

        if (!isRegularFile(downloadedCliJar)) {
            final HttpUriRequest request = clientFacade.newGet(pValidatedConfig.getCliJarUri());
            try {

                try (final CloseableHttpResponse response = client.execute(request)) {
                    final StatusLine statusLine = response.getStatusLine();

                    if (statusLine.getStatusCode() != SC_OK) {
                        throw new MojoExecutionException(messages.getMessage(DOWNLOADER_ERROR_WRONG_STATUS_CODE,
                                statusLine, pValidatedConfig.getCliJarUri()));
                    }

                    final HttpEntity entity = response.getEntity();

                    if (entity != null) {
                        try (final InputStream in = entity.getContent()) {
                            copy(in, downloadedCliJar);
                        }
                    } else {
                        throw new MojoExecutionException(messages.getMessage(DOWNLOADER_ERROR_ENTITY_IS_NULL,
                                pValidatedConfig.getCliJarUri()));
                    }
                }
            } finally {
                request.abort();
            }
        }

        final String absoluteDownloadedCliPath = downloadedCliJar.toAbsolutePath().toString();

        if (pLog.isInfoEnabled()) {
            pLog.info(messages.getMessage(DOWNLOADER_INFO_USED_CLI_JAR, absoluteDownloadedCliPath));
        }

        return absoluteDownloadedCliPath;
    } catch (final IOException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException
            | CertificateException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:org.dataconservancy.access.connector.HttpDcsConnector.java

/**
 * Execute the supplied request.  Method is package-private for unit testing.
 *
 * @param req the request object// w  w  w. jav a  2 s.c o  m
 * @param success_status http response status needed for the execution to succeed 
 * @return an HttpResponse
 * @throws DcsClientFault if the response status code is between 400 to 499 inclusive
 * @throws DcsServerException if the response status code is 500 or greater
 * @throws HttpIoException if a connection cannot be obtained from the connection pool, or an I/O error occurs
 * @throws DcsConnectorRuntimeException if any other RuntimeExceptions are caught
 */
HttpResponse execute(HttpUriRequest req, int success_status) throws DcsClientFault {
    HttpResponse response = null;
    String requestUri = null;
    try {
        requestUri = req.getRequestLine().getUri();
        response = client.execute(req);
    } catch (ConnectionPoolTimeoutException e) {
        throw new HttpIoException(
                "Timeout reached while obtaining an HTTP connection from the connection pool.  "
                        + "First, ensure response InputStreams are being read (this frees the connection), then try to "
                        + "increase the maximum number of connections, or increase the connection pool timeout.",
                e);
    } catch (IOException e) {
        throw new HttpIoException("Could not retrieve " + requestUri + ": " + e.getMessage(), e);
    } catch (IllegalStateException e) {
        // thrown when trying to re-use a connection that hasn't been closed
        req.abort();
        throw new DcsClientFault(e.getMessage(), e);
    } catch (RuntimeException e) {
        req.abort();
        throw new DcsConnectorRuntimeException(e.getMessage(), e);
    }

    final int statusCode = response.getStatusLine().getStatusCode();
    final String statusReason = response.getStatusLine().getReasonPhrase();

    if (statusCode != success_status) {

        req.abort();

        if (statusCode >= 400 && statusCode < 500) {
            throw new DcsClientFault("Could not retrieve " + requestUri + ": response from server was "
                    + statusCode + " '" + statusReason + "'");
        }

        if (statusCode >= 500) {
            throw new DcsServerException("Could not retrieve " + requestUri + ": response from server was "
                    + statusCode + " '" + statusReason + "'");
        }

        if (statusCode > 200 && statusCode < 300) {
            log.debug("Received status {} for {}", statusCode, requestUri);
            // TODO
        }

        if (statusCode >= 300 && statusCode < 400) {
            log.debug("Received status {} for {}", statusCode, requestUri);
            // TODO
        }

        if (statusCode >= 100 && statusCode < 200) {
            log.debug("Received status {} for {}", statusCode, requestUri);
            // TODO
        }
    }

    return response;
}

From source file:com.piusvelte.sonet.core.SonetHttpClient.java

protected static String httpResponse(HttpClient httpClient, HttpUriRequest httpRequest) {
    String response = null;/* w w w  .java2s .  c om*/
    if (httpClient != null) {
        HttpResponse httpResponse;
        HttpEntity entity = null;
        try {
            httpResponse = httpClient.execute(httpRequest);
            StatusLine statusLine = httpResponse.getStatusLine();
            entity = httpResponse.getEntity();

            switch (statusLine.getStatusCode()) {
            case 200:
            case 201:
            case 204:
                if (entity != null) {
                    InputStream is = entity.getContent();
                    ByteArrayOutputStream content = new ByteArrayOutputStream();
                    byte[] sBuffer = new byte[512];
                    int readBytes = 0;
                    while ((readBytes = is.read(sBuffer)) != -1) {
                        content.write(sBuffer, 0, readBytes);
                    }
                    response = new String(content.toByteArray());
                } else {
                    response = "OK";
                }
                break;
            default:
                Log.e(TAG, httpRequest.getURI().toString());
                Log.e(TAG, "" + statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());
                if (entity != null) {
                    InputStream is = entity.getContent();
                    ByteArrayOutputStream content = new ByteArrayOutputStream();
                    byte[] sBuffer = new byte[512];
                    int readBytes = 0;
                    while ((readBytes = is.read(sBuffer)) != -1) {
                        content.write(sBuffer, 0, readBytes);
                    }
                    Log.e(TAG, "response:" + new String(content.toByteArray()));
                }
                break;
            }
        } catch (ClientProtocolException e) {
            Log.e(TAG, e.toString());
            try {
                httpRequest.abort();
            } catch (UnsupportedOperationException ignore) {
                Log.e(TAG, ignore.toString());
            }
        } catch (IllegalStateException e) {
            Log.e(TAG, e.toString());
            try {
                httpRequest.abort();
            } catch (UnsupportedOperationException ignore) {
                Log.e(TAG, ignore.toString());
            }
        } catch (IOException e) {
            Log.e(TAG, e.toString());
            try {
                httpRequest.abort();
            } catch (UnsupportedOperationException ignore) {
                Log.e(TAG, ignore.toString());
            }
        } finally {
            if (entity != null) {
                try {
                    entity.consumeContent();
                } catch (IOException e) {
                    Log.e(TAG, e.toString());
                }
            }
        }
    }
    return response;
}

From source file:com.soundcloud.playerapi.ApiWrapper.java

public HttpResponse safeExecute(HttpHost target, HttpUriRequest request) throws IOException {
    if (target == null) {
        target = determineTarget(request);
    }//  ww  w .j  a  va  2  s.  com

    try {
        return getHttpClient().execute(target, request);
    } catch (NullPointerException e) {
        // this is a workaround for a broken httpclient version,
        // cf. http://code.google.com/p/android/issues/detail?id=5255
        // NPE in DefaultRequestDirector.java:456
        if (!request.isAborted() && request.getParams().isParameterFalse("npe-retried")) {
            request.getParams().setBooleanParameter("npe-retried", true);
            return safeExecute(target, request);
        } else {
            request.abort();
            throw new BrokenHttpClientException(e);
        }
    } catch (IllegalArgumentException e) {
        // more brokenness
        // cf. http://code.google.com/p/android/issues/detail?id=2690
        request.abort();
        throw new BrokenHttpClientException(e);
    } catch (ArrayIndexOutOfBoundsException e) {
        // Caused by: java.lang.ArrayIndexOutOfBoundsException: length=7; index=-9
        // org.apache.harmony.security.asn1.DerInputStream.readBitString(DerInputStream.java:72))
        // org.apache.harmony.security.asn1.ASN1BitString.decode(ASN1BitString.java:64)
        // ...
        // org.apache.http.conn.ssl.SSLSocketFactory.createSocket(SSLSocketFactory.java:375)
        request.abort();
        throw new BrokenHttpClientException(e);
    }
}

From source file:com.example.common.ApiAsyncTask.java

@Override
protected Object doInBackground(Void... params) {

    if (!Utils.isNetworkAvailable(mContext)) {
        return TIMEOUT_ERROR;
    }/*from w w w.  j  a va 2 s . co m*/

    String requestUrl = MarketAPI.API_URLS[mReuqestAction];

    HttpEntity requestEntity = null;
    try {
        requestEntity = ApiRequestFactory.getRequestEntity(mReuqestAction, mParameter);
    } catch (UnsupportedEncodingException e) {
        Utils.D("OPPS...This device not support UTF8 encoding.[should not happend]");
        return BUSSINESS_ERROR;
    }

    Object result = null;
    //
    String cacheKey = "";
    if (!ApiRequestFactory.API_NO_CACHE_MAP.contains(mReuqestAction)) {
        final boolean isBodyEmpty = (requestEntity == null);
        if (isBodyEmpty) {
            // if no http entity then directly use the request url as cache key
            cacheKey = Utils.getMD5(requestUrl);
        } else {
            // we only cache string request
            if (requestEntity instanceof StringEntity) {
                try {
                    cacheKey = Utils.getMD5(requestUrl + EntityUtils.toString(requestEntity));
                } catch (ParseException e) {
                    Utils.W("have ParseException when get cache key", e);
                } catch (IOException e) {
                    Utils.W("have IOException when get cache key", e);
                }
            }
        }
        // fetch result from the cache
        result = mResponseCache.getResponse(cacheKey);
        if (result != null) {
            Utils.V("retrieve response from the cache");
            return result;
        }
    }

    HttpResponse response = null;
    HttpUriRequest request = null;
    try {
        request = ApiRequestFactory.getRequest(requestUrl, mReuqestAction, requestEntity, mSession);
        response = mClient.execute(request);

        final int statusCode = response.getStatusLine().getStatusCode();
        Utils.D("requestUrl " + requestUrl + " statusCode: " + statusCode);

        if (HttpStatus.SC_OK != statusCode) {
            // 
            return statusCode;
        }

        // fetch result from remote server
        result = ApiResponseFactory.getResponse(mContext, mReuqestAction, response);
        if (result != null && !ApiRequestFactory.API_NO_CACHE_MAP.contains(mReuqestAction)) {
            mResponseCache.putResponse(cacheKey, result);
        }
        // API ResponseBUSSINESS_ERROR610
        return result == null ? BUSSINESS_ERROR : result;

    } catch (IOException e) {
        Utils.D("Market API encounter the IO exception[mostly is timeout exception]", e);
        return TIMEOUT_ERROR;
    } finally {
        // release the connection
        if (request != null) {
            request.abort();
        }
        if (response != null) {
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    entity.consumeContent();
                }
            } catch (IOException e) {
                Utils.D("release low-level resource error");
            }
        }
    }
}

From source file:com.mappn.gfan.common.ApiAsyncTask.java

@Override
protected Object doInBackground(Void... params) {

    if (!Utils.isNetworkAvailable(mContext)) {
        return TIMEOUT_ERROR;
    }//from ww  w .j a v a 2  s.  c om

    String requestUrl = MarketAPI.API_URLS[mReuqestAction];

    HttpEntity requestEntity = null;
    try {
        requestEntity = ApiRequestFactory.getRequestEntity(mReuqestAction, mParameter);
    } catch (UnsupportedEncodingException e) {
        Utils.D("OPPS...This device not support UTF8 encoding.[should not happend]");
        return BUSSINESS_ERROR;
    }

    Object result = null;
    //
    String cacheKey = "";
    if (!ApiRequestFactory.API_NO_CACHE_MAP.contains(mReuqestAction)) {
        final boolean isBodyEmpty = (requestEntity == null);
        if (isBodyEmpty) {
            // if no http entity then directly use the request url as cache key
            cacheKey = Utils.getMD5(requestUrl);
        } else {
            // we only cache string request
            if (requestEntity instanceof StringEntity) {
                try {
                    cacheKey = Utils.getMD5(requestUrl + EntityUtils.toString(requestEntity));
                } catch (ParseException e) {
                    Utils.W("have ParseException when get cache key", e);
                } catch (IOException e) {
                    Utils.W("have IOException when get cache key", e);
                }
            }
        }
        // fetch result from the cache
        result = mResponseCache.getResponse(cacheKey);
        if (result != null) {
            Utils.V("retrieve response from the cache");
            return result;
        }
    }

    HttpResponse response = null;
    HttpUriRequest request = null;
    try {
        request = ApiRequestFactory.getRequest(requestUrl, mReuqestAction, requestEntity, mSession);
        response = mClient.execute(request);

        final int statusCode = response.getStatusLine().getStatusCode();
        Utils.D("requestUrl " + requestUrl + " statusCode: " + statusCode);

        if (HttpStatus.SC_OK != statusCode) {
            // ?
            return statusCode;
        }

        // fetch result from remote server
        result = ApiResponseFactory.getResponse(mContext, mReuqestAction, response);
        if (result != null && !ApiRequestFactory.API_NO_CACHE_MAP.contains(mReuqestAction)) {
            mResponseCache.putResponse(cacheKey, result);
        }
        // ?API Response?BUSSINESS_ERROR?610
        return result == null ? BUSSINESS_ERROR : result;

    } catch (IOException e) {
        Utils.D("Market API encounter the IO exception[mostly is timeout exception]", e);
        return TIMEOUT_ERROR;
    } finally {
        // release the connection
        if (request != null) {
            request.abort();
        }
        if (response != null) {
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    entity.consumeContent();
                }
            } catch (IOException e) {
                Utils.D("release low-level resource error");
            }
        }
    }
}