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.gsma.mobileconnect.utils.RestClient.java

/**
 * Execute the given request./*  w w w .j  av a 2 s  .c  o  m*/
 * <p>
 * Abort the request if it exceeds the specified timeout.
 *
 * @param httpClient The client to use.
 * @param request The request to make.
 * @param context The context to use.
 * @param timeout The timeout to use.
 * @return A Http Response.
 * @throws RestException Thrown if the request fails or times out.
 */
private CloseableHttpResponse executeRequest(CloseableHttpClient httpClient, final HttpRequestBase request,
        HttpClientContext context, int timeout) throws RestException {
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            request.abort();
        }
    }, timeout);

    RequestConfig localConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout)
            .setConnectTimeout(timeout).setSocketTimeout(timeout).setCookieSpec(CookieSpecs.STANDARD).build();
    request.setConfig(localConfig);
    try {
        return httpClient.execute(request, context);
    } catch (IOException ex) {
        String requestUri = request.getURI().toString();
        if (request.isAborted()) {
            throw new RestException("Rest end point did not respond", requestUri);
        }
        throw new RestException("Rest call failed", requestUri, ex);
    }
}

From source file:ee.ria.xroad.common.util.AsyncHttpSender.java

private void doRequest(HttpRequestBase request) throws Exception {
    this.request = request;

    addAdditionalHeaders();//from  www  .  j a v  a2s.c o  m
    try {
        futureResponse = client.execute(request, context, new Callback());
    } catch (Exception ex) {
        LOG.debug("Request failed", ex);
        request.abort();
        throw ex;
    }
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.HttpClientRequestTransport.java

public void abortRequest(SubmitContext submitContext) {
    HttpRequestBase postMethod = (HttpRequestBase) submitContext.getProperty(HTTP_METHOD);
    if (postMethod != null)
        postMethod.abort();
}

From source file:CB_Utils.http.HttpUtils.java

/**
 * Executes a HTTP request and returns the response as a string. As a HttpRequestBase is given, a HttpGet or HttpPost be passed for
 * execution.<br>/*from  w  w w . j  a v  a 2s.  co  m*/
 * <br>
 * Over the ICancel interface cycle is queried in 200 mSec, if the download should be canceled!<br>
 * Can be NULL
 * 
 * @param httprequest
 *            HttpRequestBase
 * @param icancel
 *            ICancel interface (maybe NULL)
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 * @throws ConnectTimeoutException
 */
public static String Execute(final HttpRequestBase httprequest, final ICancel icancel)
        throws IOException, ClientProtocolException, ConnectTimeoutException {

    httprequest.setHeader("Accept", "application/json");
    httprequest.setHeader("Content-type", "application/json");

    // Execute HTTP Post Request
    String result = "";

    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.

    HttpConnectionParams.setConnectionTimeout(httpParameters, conectionTimeout);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.

    HttpConnectionParams.setSoTimeout(httpParameters, socketTimeout);

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

    final AtomicBoolean ready = new AtomicBoolean(false);
    if (icancel != null) {
        Thread cancelChekThread = new Thread(new Runnable() {
            @Override
            public void run() {
                do {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                    }
                    if (icancel.cancel())
                        httprequest.abort();
                } while (!ready.get());
            }
        });
        cancelChekThread.start();// start abort chk thread
    }
    HttpResponse response = httpClient.execute(httprequest);
    ready.set(true);// cancel abort chk thread

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String line = "";
    while ((line = rd.readLine()) != null) {
        if (Plattform.used == Plattform.Server)
            line = new String(line.getBytes("ISO-8859-1"), "UTF-8");
        result += line + "\n";
    }
    return result;
}

From source file:org.apache.wink.client.internal.handlers.httpclient.ApacheHttpClientConnectionHandler.java

private HttpResponse processRequest(ClientRequest request, HandlerContext context)
        throws IOException, KeyManagementException, NoSuchAlgorithmException {
    HttpClient client = openConnection(request);
    // TODO: move this functionality to the base class
    NonCloseableOutputStream ncos = new NonCloseableOutputStream();
    OutputStream os = ncos;/*  w w  w . ja v a 2  s .  co m*/

    EntityWriter entityWriter = null;
    if (request.getEntity() != null) {
        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, client, entityWriter);

    try {
        return client.execute(entityRequest);
    } catch (Exception ex) {
        entityRequest.abort();
        throw new RuntimeException(ex);
    }
}

From source file:org.cogsurv.cogsurver.http.AbstractHttpApi.java

/**
 * execute() an httpRequest catching exceptions and returning null instead.
 *
 * @param httpRequest/* www.ja  v  a 2  s  .co m*/
 * @return
 * @throws IOException
 */
public HttpResponse executeHttpRequest(HttpRequestBase httpRequest) throws IOException {
    if (DEBUG)
        LOG.log(Level.FINE, "executing HttpRequest for: " + httpRequest.getURI().toString());
    try {
        mHttpClient.getConnectionManager().closeExpiredConnections();
        return mHttpClient.execute(httpRequest);
    } catch (IOException e) {
        httpRequest.abort();
        throw e;
    }
}

From source file:com.cloudant.client.org.lightcouch.CouchDbClientBase.java

/**
 * Executes a HTTP request./*from  ww w .j  a  v  a 2s  .  co  m*/
 * <p><b>Note</b>: The response must be closed after use to release the connection.
 *
 * @param request The HTTP request to execute.
 * @return {@link HttpResponse}
 */
public HttpResponse executeRequest(HttpRequestBase request) {
    try {
        return httpClient.execute(host, request, createContext());
    } catch (IOException e) {
        request.abort();
        throw new CouchDbException("Error executing request. ", e);
    }

}

From source file:com.samknows.measurement.net.Connection.java

private HttpResponse doRequest(HttpRequestBase request) throws ConnectionException, LoginException {
    HttpResponse response;/* w w w. j av  a  2  s  . c  o m*/
    try {
        Log.i(TAG, request.getURI().toString());
        response = mClient.execute(request);
    } catch (ClientProtocolException e) {
        throw new ConnectionException(e);
    } catch (IOException e) {
        throw new ConnectionException(e);
    } finally {
        request.abort();
    }
    if (response.getStatusLine().getStatusCode() != 200) {
        throw new LoginException("Could not login.");
    }
    return response;
}

From source file:net.paissad.waqtsalat.service.utils.HttpUtils.java

private static InputStream sendRequest(final String url, final RequestType requestType) throws WSException {

    InputStream in = null;// www. ja  v  a  2  s .co m
    HttpClient client = null;
    HttpRequestBase request = null;
    boolean errorOccured = false;

    try {
        request = getNewHttpRequest(url, requestType, null);
        client = getNewHttpClient();
        HttpResponse resp = client.execute(request);

        int statusCode = resp.getStatusLine().getStatusCode();

        if (statusCode == HttpStatus.SC_OK) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IOUtils.copy(resp.getEntity().getContent(), baos);
            baos.flush();
            in = new ByteArrayInputStream(baos.toByteArray());

        } else {
            // The response code is not OK.
            StringBuilder errMsg = new StringBuilder();
            errMsg.append("HTTP ").append(requestType).append(" failed => ").append(resp.getStatusLine());
            if (request != null) {
                errMsg.append(" : ").append(request.getURI());
            }
            throw new WSException(errMsg.toString());
        }

        return in;

    } catch (Exception e) {
        errorOccured = true;
        throw new WSException("Error during file HTTP request.", e);

    } finally {
        if (errorOccured) {
            if (request != null) {
                request.abort();
            }
        }
        if (client != null) {
            client.getConnectionManager().shutdown();
        }
    }
}

From source file:com.aliyun.oss.common.comm.DefaultServiceClient.java

@Override
public ResponseMessage sendRequestCore(ServiceClient.Request request, ExecutionContext context)
        throws IOException {
    HttpRequestBase httpRequest = httpRequestFactory.createHttpRequest(request, context);
    setProxyAuthorizationIfNeed(httpRequest);
    HttpClientContext httpContext = createHttpContext();
    httpContext.setRequestConfig(this.requestConfig);

    CloseableHttpResponse httpResponse = null;
    try {//ww  w .ja v a 2s.  co  m
        httpResponse = httpClient.execute(httpRequest, httpContext);
    } catch (IOException ex) {
        httpRequest.abort();
        throw ExceptionFactory.createNetworkException(ex);
    }

    return buildResponse(request, httpResponse);
}