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
}
}
}
}
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
}
}
}
}
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;
}
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;
}
}
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);
}
Aggregations