Search in sources :

Example 26 with HttpRequestBase

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

the class HttpPollingConsumer method doReceive.

protected Exchange doReceive(int timeout) {
    Exchange exchange = endpoint.createExchange();
    HttpRequestBase method = createMethod(exchange);
    HttpClientContext httpClientContext = new HttpClientContext();
    // set optional timeout in millis
    if (timeout > 0) {
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).build();
        httpClientContext.setRequestConfig(requestConfig);
    }
    HttpEntity responeEntity = null;
    try {
        // execute request
        HttpResponse response = httpClient.execute(method, httpClientContext);
        int responseCode = response.getStatusLine().getStatusCode();
        responeEntity = response.getEntity();
        Object body = HttpHelper.readResponseBodyFromInputStream(responeEntity.getContent(), exchange);
        // lets store the result in the output message.
        Message message = exchange.getOut();
        message.setBody(body);
        // lets set the headers
        Header[] headers = response.getAllHeaders();
        HeaderFilterStrategy strategy = endpoint.getHeaderFilterStrategy();
        for (Header header : headers) {
            String name = header.getName();
            // mapping the content-type
            if (name.toLowerCase().equals("content-type")) {
                name = Exchange.CONTENT_TYPE;
            }
            String value = header.getValue();
            if (strategy != null && !strategy.applyFilterToExternalHeaders(name, value, exchange)) {
                message.setHeader(name, value);
            }
        }
        message.setHeader(Exchange.HTTP_RESPONSE_CODE, responseCode);
        if (response.getStatusLine() != null) {
            message.setHeader(Exchange.HTTP_RESPONSE_TEXT, response.getStatusLine().getReasonPhrase());
        }
        return exchange;
    } catch (IOException e) {
        throw new RuntimeCamelException(e);
    } finally {
        if (responeEntity != null) {
            try {
                EntityUtils.consume(responeEntity);
            } catch (IOException e) {
            // nothing what we can do
            }
        }
    }
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpEntity(org.apache.http.HttpEntity) Message(org.apache.camel.Message) HttpResponse(org.apache.http.HttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) HeaderFilterStrategy(org.apache.camel.spi.HeaderFilterStrategy) IOException(java.io.IOException) Exchange(org.apache.camel.Exchange) Header(org.apache.http.Header) RuntimeCamelException(org.apache.camel.RuntimeCamelException)

Example 27 with HttpRequestBase

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

the class HttpProducer method process.

public void process(Exchange exchange) throws Exception {
    if (getEndpoint().isClearExpiredCookies() && !getEndpoint().isBridgeEndpoint()) {
        // create the cookies before the invocation
        getEndpoint().getCookieStore().clearExpired(new Date());
    }
    // if we bridge endpoint then we need to skip matching headers with the HTTP_QUERY to avoid sending
    // duplicated headers to the receiver, so use this skipRequestHeaders as the list of headers to skip
    Map<String, Object> skipRequestHeaders = null;
    if (getEndpoint().isBridgeEndpoint()) {
        exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE);
        String queryString = exchange.getIn().getHeader(Exchange.HTTP_QUERY, String.class);
        if (queryString != null) {
            skipRequestHeaders = URISupport.parseQuery(queryString, false, true);
        }
    }
    HttpRequestBase httpRequest = createMethod(exchange);
    Message in = exchange.getIn();
    String httpProtocolVersion = in.getHeader(Exchange.HTTP_PROTOCOL_VERSION, String.class);
    if (httpProtocolVersion != null) {
        // set the HTTP protocol version
        int[] version = HttpHelper.parserHttpVersion(httpProtocolVersion);
        httpRequest.setProtocolVersion(new HttpVersion(version[0], version[1]));
    }
    HeaderFilterStrategy strategy = getEndpoint().getHeaderFilterStrategy();
    // propagate headers as HTTP headers
    for (Map.Entry<String, Object> entry : in.getHeaders().entrySet()) {
        String key = entry.getKey();
        Object headerValue = in.getHeader(key);
        if (headerValue != null) {
            // use an iterator as there can be multiple values. (must not use a delimiter, and allow empty values)
            final Iterator<?> it = ObjectHelper.createIterator(headerValue, null, true);
            // the value to add as request header
            final List<String> values = new ArrayList<String>();
            // should be combined into a single value
            while (it.hasNext()) {
                String value = exchange.getContext().getTypeConverter().convertTo(String.class, it.next());
                // as then we would duplicate headers on both the endpoint uri, and in HTTP headers as well
                if (skipRequestHeaders != null && skipRequestHeaders.containsKey(key)) {
                    continue;
                }
                if (value != null && strategy != null && !strategy.applyFilterToCamelHeaders(key, value, exchange)) {
                    values.add(value);
                }
            }
            // add the value(s) as a http request header
            if (values.size() > 0) {
                // use the default toString of a ArrayList to create in the form [xxx, yyy]
                // if multi valued, for a single value, then just output the value as is
                String s = values.size() > 1 ? values.toString() : values.get(0);
                httpRequest.addHeader(key, s);
            }
        }
    }
    if (getEndpoint().getCookieHandler() != null) {
        Map<String, List<String>> cookieHeaders = getEndpoint().getCookieHandler().loadCookies(exchange, httpRequest.getURI());
        for (Map.Entry<String, List<String>> entry : cookieHeaders.entrySet()) {
            String key = entry.getKey();
            if (entry.getValue().size() > 0) {
                // use the default toString of a ArrayList to create in the form [xxx, yyy]
                // if multi valued, for a single value, then just output the value as is
                String s = entry.getValue().size() > 1 ? entry.getValue().toString() : entry.getValue().get(0);
                httpRequest.addHeader(key, s);
            }
        }
    }
    //if this option is set, and the exchange Host header is not null, we will set it's current value on the httpRequest
    if (getEndpoint().isPreserveHostHeader()) {
        String hostHeader = exchange.getIn().getHeader("Host", String.class);
        if (hostHeader != null) {
            //HttpClient 4 will check to see if the Host header is present, and use it if it is, see org.apache.http.protocol.RequestTargetHost in httpcore
            httpRequest.setHeader("Host", hostHeader);
        }
    }
    if (getEndpoint().isConnectionClose()) {
        httpRequest.addHeader("Connection", HTTP.CONN_CLOSE);
    }
    // lets store the result in the output message.
    HttpResponse httpResponse = null;
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Executing http {} method: {}", httpRequest.getMethod(), httpRequest.getURI().toString());
        }
        httpResponse = executeMethod(httpRequest);
        int responseCode = httpResponse.getStatusLine().getStatusCode();
        LOG.debug("Http responseCode: {}", responseCode);
        if (!throwException) {
            // if we do not use failed exception then populate response for all response codes
            populateResponse(exchange, httpRequest, httpResponse, in, strategy, responseCode);
        } else {
            boolean ok = HttpHelper.isStatusCodeOk(responseCode, getEndpoint().getOkStatusCodeRange());
            if (ok) {
                // only populate response for OK response
                populateResponse(exchange, httpRequest, httpResponse, in, strategy, responseCode);
            } else {
                // operation failed so populate exception to throw
                throw populateHttpOperationFailedException(exchange, httpRequest, httpResponse, responseCode);
            }
        }
    } finally {
        final HttpResponse response = httpResponse;
        if (httpResponse != null && getEndpoint().isDisableStreamCache()) {
            // close the stream at the end of the exchange to ensure it gets eventually closed later
            exchange.addOnCompletion(new SynchronizationAdapter() {

                @Override
                public void onDone(Exchange exchange) {
                    try {
                        EntityUtils.consume(response.getEntity());
                    } catch (Throwable e) {
                    // ignore
                    }
                }
            });
        } else if (httpResponse != null) {
            // close the stream now
            try {
                EntityUtils.consume(response.getEntity());
            } catch (Throwable e) {
            // ignore
            }
        }
    }
}
Also used : HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) Message(org.apache.camel.Message) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) HeaderFilterStrategy(org.apache.camel.spi.HeaderFilterStrategy) HttpProtocolHeaderFilterStrategy(org.apache.camel.http.common.HttpProtocolHeaderFilterStrategy) Date(java.util.Date) Exchange(org.apache.camel.Exchange) List(java.util.List) ArrayList(java.util.ArrayList) HttpVersion(org.apache.http.HttpVersion) Map(java.util.Map) HashMap(java.util.HashMap) SynchronizationAdapter(org.apache.camel.support.SynchronizationAdapter)

Example 28 with HttpRequestBase

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

the class HttpProducer method createMethod.

/**
     * Creates the HttpMethod to use to call the remote server, either its GET or POST.
     *
     * @param exchange the exchange
     * @return the created method as either GET or POST
     * @throws URISyntaxException is thrown if the URI is invalid
     * @throws Exception is thrown if error creating RequestEntity
     */
protected HttpRequestBase createMethod(Exchange exchange) throws Exception {
    // creating the url to use takes 2-steps
    String url = HttpHelper.createURL(exchange, getEndpoint());
    URI uri = HttpHelper.createURI(exchange, url, getEndpoint());
    // get the url from the uri
    url = uri.toASCIIString();
    // execute any custom url rewrite
    String rewriteUrl = HttpHelper.urlRewrite(exchange, url, getEndpoint(), this);
    if (rewriteUrl != null) {
        // update url and query string from the rewritten url
        url = rewriteUrl;
        uri = new URI(url);
    }
    // create http holder objects for the request
    HttpEntity requestEntity = createRequestEntity(exchange);
    HttpMethods methodToUse = HttpMethodHelper.createMethod(exchange, getEndpoint(), requestEntity != null);
    HttpRequestBase method = methodToUse.createMethod(url);
    // special for HTTP DELETE if the message body should be included
    if (getEndpoint().isDeleteWithBody() && "DELETE".equals(method.getMethod())) {
        method = new HttpDeleteWithBodyMethod(url, requestEntity);
    }
    LOG.trace("Using URL: {} with method: {}", url, method);
    if (methodToUse.isEntityEnclosing()) {
        ((HttpEntityEnclosingRequestBase) method).setEntity(requestEntity);
        if (requestEntity != null && requestEntity.getContentType() == null) {
            LOG.debug("No Content-Type provided for URL: {} with exchange: {}", url, exchange);
        }
    }
    // there must be a host on the method
    if (method.getURI().getScheme() == null || method.getURI().getHost() == null) {
        throw new IllegalArgumentException("Invalid uri: " + uri + ". If you are forwarding/bridging http endpoints, then enable the bridgeEndpoint option on the endpoint: " + getEndpoint());
    }
    return method;
}
Also used : HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) HttpEntity(org.apache.http.HttpEntity) URI(java.net.URI)

Example 29 with HttpRequestBase

use of org.apache.http.client.methods.HttpRequestBase in project 9GAG by Mixiaoxiao.

the class HttpClientUtil method download.

/**
	 * <pre>���d</pre>
	 * 
	 * @param url
	 * @param saveFile
	 * @param params
	 * @param isPost
	 * @return ���saveFile==null�t�؂�inputstream, ��t�؂�saveFile
	 * @throws Exception
	 */
public static Object download(final String url, final File saveFile, final Map<String, String> params, final boolean isPost) throws Exception {
    boolean saveToFile = saveFile != null;
    // check dir exist ??
    if (saveToFile && saveFile.getParentFile().exists() == false) {
        saveFile.getParentFile().mkdirs();
    }
    Exception err = null;
    HttpRequestBase request = null;
    HttpResponse response = null;
    HttpEntity entity = null;
    FileOutputStream fos = null;
    Object result = null;
    try {
        // create request
        if (isPost) {
            request = new HttpPost(url);
        } else {
            request = new HttpGet(url);
        }
        // add header & params
        addHeaderAndParams(request, params);
        // connect
        response = httpclient.execute(request);
        entity = response.getEntity();
        entity = new BufferedHttpEntity(entity);
        // get result
        if (saveToFile) {
            // save to disk
            fos = new FileOutputStream(saveFile);
            IOUtils.copy(entity.getContent(), fos);
            result = saveFile;
        } else {
            // warp to inpustream
            result = new BufferedInputStream(entity.getContent());
        }
    } catch (Exception e) {
        err = e;
    } finally {
        // close
        IOUtils.closeQuietly(fos);
        // clear
        request = null;
        response = null;
        entity = null;
        if (err != null) {
            throw err;
        }
        return result;
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) BufferedInputStream(java.io.BufferedInputStream) FileOutputStream(java.io.FileOutputStream) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse)

Example 30 with HttpRequestBase

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

the class RequestProcessorChain method onInitiate.

/**
	 * <p>Accepts the {@link InvocationContext} given to {@link #run(Object...)}} the {@link RequestProcessorChain} 
	 * and translates the request metadata to a concrete instance of {@link HttpRequestBase}. The 
	 * {@link HttpRequestBase}, together with the {@link InvocationContext} is then given to the root link 
	 * which runs the {@link UriProcessor} and returns the resulting {@link HttpRequestBase}.</p> 
	 * 
	 * <p>See {@link AbstractRequestProcessor}.</p>
	 * 
	 * {@inheritDoc}
	 */
@Override
protected HttpRequestBase onInitiate(ProcessorChainLink<HttpRequestBase, RequestProcessorException> root, Object... args) {
    InvocationContext context = assertAssignable(assertNotEmpty(args)[0], InvocationContext.class);
    HttpRequestBase request = RequestUtils.translateRequestMethod(context);
    //allow any exceptions to elevate to a chain-wide failure
    return root.getProcessor().run(context, request);
}
Also used : HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) InvocationContext(com.lonepulse.robozombie.proxy.InvocationContext)

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