use of org.apache.http.message.BasicHttpEntityEnclosingRequest in project LogHub by fbacchella.
the class AbstractHttpSender method doRequest.
protected HttpResponse doRequest(HttpRequest therequest) {
CloseableHttpResponse response = null;
HttpClientContext context = HttpClientContext.create();
if (credsProvider != null) {
context.setCredentialsProvider(credsProvider);
}
HttpHost host;
RequestLine requestLine = new BasicRequestLine(therequest.verb, therequest.url.getPath(), therequest.httpVersion);
BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest(requestLine);
if (therequest.content != null) {
request.setEntity(therequest.content);
}
therequest.headers.forEach((i, j) -> request.addHeader(i, j));
host = new HttpHost(therequest.url.getHost(), therequest.url.getPort(), therequest.url.getProtocol());
try {
response = client.execute(host, request, context);
} catch (ConnectionPoolTimeoutException e) {
logger.error("Connection to {} timed out", host);
return new HttpResponse(host, null, e, null);
} catch (HttpHostConnectException e) {
String message = "";
try {
throw e.getCause();
} catch (ConnectException e1) {
message = String.format("Connection to %s refused", host);
} catch (SocketTimeoutException e1) {
message = String.format("Slow response from %s", host);
} catch (Throwable e1) {
message = String.format("Connection to %s failed: %s", host, e1.getMessage());
logger.catching(Level.DEBUG, e1);
}
logger.error(message);
logger.catching(Level.DEBUG, e.getCause());
return new HttpResponse(host, null, e, null);
} catch (IOException e) {
Throwable rootCause = e;
while (rootCause.getCause() != null) {
rootCause = rootCause.getCause();
}
;
// A TLS exception, will not help to retry
if (rootCause instanceof GeneralSecurityException) {
logger.error("Secure comunication with {} failed: {}", host, rootCause.getMessage());
logger.catching(Level.DEBUG, rootCause);
return new HttpResponse(host, null, null, (GeneralSecurityException) rootCause);
} else {
logger.error("Comunication with {} failed: {}", host, e.getMessage());
logger.catching(Level.DEBUG, e);
return new HttpResponse(host, null, e, null);
}
}
if (response == null) {
logger.error("give up trying to connect to " + getPublishName());
return null;
}
;
return new HttpResponse(host, response, null, null);
}
use of org.apache.http.message.BasicHttpEntityEnclosingRequest in project wso2-synapse by wso2.
the class Axis2HttpRequest method getRequest.
/**
* Create and return a new HttpPost request to the destination EPR
*
* @return the HttpRequest to be sent out
* @throws IOException in error retrieving the <code>HttpRequest</code>
*/
public HttpRequest getRequest() throws IOException, HttpException {
String httpMethod = (String) msgContext.getProperty(Constants.Configuration.HTTP_METHOD);
if (httpMethod == null) {
httpMethod = "POST";
}
endpointURLPrefix = (String) msgContext.getProperty(NhttpConstants.ENDPOINT_PREFIX);
boolean forceHTTP10 = msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0);
HttpVersion httpver = forceHTTP10 ? HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1;
HttpRequest httpRequest;
try {
if ("POST".equals(httpMethod) || "PUT".equals(httpMethod) || "PATCH".equals(httpMethod)) {
URI uri = rewriteRequestURI(new URI(epr.getAddress()));
BasicHttpEntityEnclosingRequest requestWithEntity = new BasicHttpEntityEnclosingRequest(httpMethod, uri.toASCIIString(), httpver);
BasicHttpEntity entity = new BasicHttpEntity();
if (forceHTTP10) {
setStreamAsTempData(entity);
} else {
entity.setChunked(chunked);
if (!chunked) {
setStreamAsTempData(entity);
}
}
requestWithEntity.setEntity(entity);
requestWithEntity.setHeader(HTTP.CONTENT_TYPE, messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction()));
httpRequest = requestWithEntity;
} else if ("GET".equals(httpMethod) || "DELETE".equals(httpMethod)) {
URL url = messageFormatter.getTargetAddress(msgContext, format, new URL(epr.getAddress()));
URI uri = rewriteRequestURI(url.toURI());
httpRequest = new BasicHttpRequest(httpMethod, uri.toASCIIString(), httpver);
/*GETs and DELETEs do not need Content-Type headers because they do not have payloads*/
// httpRequest.setHeader(HTTP.CONTENT_TYPE, messageFormatter.getContentType(
// msgContext, format, msgContext.getSoapAction()));
} else {
URI uri = rewriteRequestURI(new URI(epr.getAddress()));
httpRequest = new BasicHttpRequest(httpMethod, uri.toASCIIString(), httpver);
}
} catch (URISyntaxException ex) {
throw new HttpException(ex.getMessage(), ex);
}
// set any transport headers
Object o = msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
if (o != null && o instanceof Map) {
Map headers = (Map) o;
for (Object header : headers.keySet()) {
Object value = headers.get(header);
if (header instanceof String && value != null && value instanceof String) {
if (!HTTPConstants.HEADER_HOST.equalsIgnoreCase((String) header)) {
httpRequest.setHeader((String) header, (String) value);
String excessProp = NhttpConstants.EXCESS_TRANSPORT_HEADERS;
Map map = (Map) msgContext.getProperty(excessProp);
if (map != null && map.get(header) != null) {
log.debug("Number of excess values for " + header + " header is : " + ((Collection) (map.get(header))).size());
for (Iterator iterator = map.keySet().iterator(); iterator.hasNext(); ) {
String key = (String) iterator.next();
for (String excessVal : (Collection<String>) map.get(key)) {
httpRequest.addHeader((String) header, (String) excessVal);
}
}
}
} else {
if (msgContext.getProperty(NhttpConstants.REQUEST_HOST_HEADER) != null) {
httpRequest.setHeader((String) header, (String) msgContext.getProperty(NhttpConstants.REQUEST_HOST_HEADER));
}
}
}
}
}
// if the message is SOAP 11 (for which a SOAPAction is *required*), and
// the msg context has a SOAPAction or a WSA-Action (give pref to SOAPAction)
// use that over any transport header that may be available
String soapAction = msgContext.getSoapAction();
if (soapAction == null) {
soapAction = msgContext.getWSAAction();
}
if (soapAction == null) {
msgContext.getAxisOperation().getInputAction();
}
if (msgContext.isSOAP11() && soapAction != null && soapAction.length() >= 0) {
Header existingHeader = httpRequest.getFirstHeader(HTTPConstants.HEADER_SOAP_ACTION);
if (existingHeader != null) {
httpRequest.removeHeader(existingHeader);
}
httpRequest.setHeader(HTTPConstants.HEADER_SOAP_ACTION, messageFormatter.formatSOAPAction(msgContext, null, soapAction));
}
if (NHttpConfiguration.getInstance().isKeepAliveDisabled() || msgContext.isPropertyTrue(NhttpConstants.NO_KEEPALIVE)) {
httpRequest.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
}
return httpRequest;
}
use of org.apache.http.message.BasicHttpEntityEnclosingRequest in project wso2-synapse by wso2.
the class TargetRequest method start.
public void start(NHttpClientConnection conn) throws IOException, HttpException {
if (pipe != null) {
TargetContext.get(conn).setWriter(pipe);
}
String path = fullUrl || (route.getProxyHost() != null && !route.isTunnelled()) ? url.toString() : url.getPath() + (url.getQuery() != null ? "?" + url.getQuery() : "");
long contentLength = -1;
String contentLengthHeader = null;
LinkedHashSet<String> httpContentLengthHeader = headers.get(HTTP.CONTENT_LEN);
if (httpContentLengthHeader != null && httpContentLengthHeader.iterator().hasNext()) {
contentLengthHeader = httpContentLengthHeader.iterator().next();
}
if (contentLengthHeader != null) {
contentLength = Long.parseLong(contentLengthHeader);
headers.remove(HTTP.CONTENT_LEN);
}
MessageContext requestMsgCtx = TargetContext.get(conn).getRequestMsgCtx();
if (requestMsgCtx.getProperty(PassThroughConstants.PASSTROUGH_MESSAGE_LENGTH) != null) {
contentLength = (Long) requestMsgCtx.getProperty(PassThroughConstants.PASSTROUGH_MESSAGE_LENGTH);
}
// fix for POST_TO_URI
if (requestMsgCtx.isPropertyTrue(NhttpConstants.POST_TO_URI)) {
path = url.toString();
}
// fix GET request empty body
if ((PassThroughConstants.HTTP_GET.equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD))) || (RelayUtils.isDeleteRequestWithoutPayload(requestMsgCtx))) {
hasEntityBody = false;
MessageFormatter formatter = MessageProcessorSelector.getMessageFormatter(requestMsgCtx);
OMOutputFormat format = PassThroughTransportUtils.getOMOutputFormat(requestMsgCtx);
if (formatter != null && format != null) {
URL _url = formatter.getTargetAddress(requestMsgCtx, format, url);
if (_url != null && !_url.toString().isEmpty()) {
if (requestMsgCtx.getProperty(NhttpConstants.POST_TO_URI) != null && Boolean.TRUE.toString().equals(requestMsgCtx.getProperty(NhttpConstants.POST_TO_URI))) {
path = _url.toString();
} else {
path = _url.getPath() + ((_url.getQuery() != null && !_url.getQuery().isEmpty()) ? ("?" + _url.getQuery()) : "");
}
}
headers.remove(HTTP.CONTENT_TYPE);
}
}
Object o = requestMsgCtx.getProperty(MessageContext.TRANSPORT_HEADERS);
if (o != null && o instanceof TreeMap) {
Map _headers = (Map) o;
String trpContentType = (String) _headers.get(HTTP.CONTENT_TYPE);
if (trpContentType != null && !trpContentType.equals("")) {
if (!TargetRequestFactory.isMultipartContent(trpContentType) && !requestMsgCtx.isDoingSwA()) {
addHeader(HTTP.CONTENT_TYPE, trpContentType);
}
}
}
if (hasEntityBody) {
request = new BasicHttpEntityEnclosingRequest(method, path, version != null ? version : HttpVersion.HTTP_1_1);
BasicHttpEntity entity = new BasicHttpEntity();
boolean forceContentLength = requestMsgCtx.isPropertyTrue(NhttpConstants.FORCE_HTTP_CONTENT_LENGTH);
boolean forceContentLengthCopy = requestMsgCtx.isPropertyTrue(PassThroughConstants.COPY_CONTENT_LENGTH_FROM_INCOMING);
if (forceContentLength) {
entity.setChunked(false);
if (forceContentLengthCopy && contentLength != -1) {
entity.setContentLength(contentLength);
}
} else {
if (contentLength != -1) {
entity.setChunked(false);
entity.setContentLength(contentLength);
} else {
entity.setChunked(chunk);
}
}
((BasicHttpEntityEnclosingRequest) request).setEntity(entity);
} else {
request = new BasicHttpRequest(method, path, version != null ? version : HttpVersion.HTTP_1_1);
}
Set<Map.Entry<String, LinkedHashSet<String>>> entries = headers.entrySet();
for (Map.Entry<String, LinkedHashSet<String>> entry : entries) {
if (entry.getKey() != null) {
Iterator<String> i = entry.getValue().iterator();
while (i.hasNext()) {
request.addHeader(entry.getKey(), i.next());
}
}
}
// setup wsa action..
if (request != null) {
String soapAction = requestMsgCtx.getSoapAction();
if (soapAction == null) {
soapAction = requestMsgCtx.getWSAAction();
requestMsgCtx.getAxisOperation().getInputAction();
}
if (requestMsgCtx.isSOAP11() && soapAction != null && soapAction.length() > 0) {
Header existingHeader = request.getFirstHeader(HTTPConstants.HEADER_SOAP_ACTION);
if (existingHeader != null) {
request.removeHeader(existingHeader);
}
MessageFormatter messageFormatter = MessageFormatterDecoratorFactory.createMessageFormatterDecorator(requestMsgCtx);
request.setHeader(HTTPConstants.HEADER_SOAP_ACTION, messageFormatter.formatSOAPAction(requestMsgCtx, null, soapAction));
// request.setHeader(HTTPConstants.USER_AGENT,"Synapse-PT-HttpComponents-NIO");
}
}
request.setParams(new DefaultedHttpParams(request.getParams(), targetConfiguration.getHttpParams()));
// Chunking is not performed for request has "http 1.0" and "GET" http method
if (!((request.getProtocolVersion().equals(HttpVersion.HTTP_1_0)) || (PassThroughConstants.HTTP_GET.equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD))) || RelayUtils.isDeleteRequestWithoutPayload(requestMsgCtx) || !(hasEntityBody))) {
this.processChunking(conn, requestMsgCtx);
}
if (!keepAlive) {
request.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
}
// Pre-process HTTP request
HttpContext httpContext = conn.getContext();
httpContext.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
if (port == -1) {
httpContext.setAttribute(ExecutionContext.HTTP_TARGET_HOST, new HttpHost(url.getHost()));
} else {
httpContext.setAttribute(ExecutionContext.HTTP_TARGET_HOST, new HttpHost(url.getHost(), port));
}
conn.getContext().setAttribute(ExecutionContext.HTTP_REQUEST, request);
httpContext.setAttribute(PassThroughConstants.PROXY_PROFILE_TARGET_HOST, requestMsgCtx.getProperty(PassThroughConstants.PROXY_PROFILE_TARGET_HOST));
// start the request
targetConfiguration.getHttpProcessor().process(request, httpContext);
if (targetConfiguration.getProxyAuthenticator() != null && route.getProxyHost() != null && !route.isTunnelled()) {
targetConfiguration.getProxyAuthenticator().authenticatePreemptively(request, httpContext);
}
conn.submitRequest(request);
if (hasEntityBody) {
TargetContext.updateState(conn, ProtocolState.REQUEST_HEAD);
} else {
TargetContext.updateState(conn, ProtocolState.REQUEST_DONE);
}
}
use of org.apache.http.message.BasicHttpEntityEnclosingRequest in project karaf by apache.
the class ProxyServlet method service.
@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException {
String[] proxyTos = proxyTo.split(",");
String actualProxy;
if (balancingPolicy != null) {
actualProxy = balancingPolicy.selectHost(proxyTos);
} else {
actualProxy = proxyTos[0];
}
URI locationUri = URI.create(actualProxy);
HttpHost host = URIUtils.extractHost(locationUri);
LOGGER.debug("Proxy to {} (host {})", locationUri, host);
String method = servletRequest.getMethod();
String proxyRequestUri = rewriteUrlFromRequest(servletRequest, actualProxy);
HttpRequest proxyRequest;
// spec: RFC 2616, sec 4.3: either of these two headers means there is a message body
if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
HttpEntityEnclosingRequest entityProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);
entityProxyRequest.setEntity(new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength()));
proxyRequest = entityProxyRequest;
} else {
proxyRequest = new BasicHttpRequest(method, proxyRequestUri);
}
copyRequestHeaders(servletRequest, proxyRequest, host);
setXForwardedForHeader(servletRequest, proxyRequest);
HttpResponse proxyResponse = null;
try {
// execute the request
proxyResponse = proxyClient.execute(host, proxyRequest);
// process the response
int statusCode = proxyResponse.getStatusLine().getStatusCode();
// copying response headers to make sure SESSIONID or other Cookie which comes from the remote host
// will be saved in client when the proxied URL was redirect to another one.
copyResponseHeaders(proxyResponse, servletRequest, servletResponse);
if (doResponseRedirect(servletRequest, servletResponse, proxyResponse, statusCode, actualProxy)) {
// the response is already "committed" now without any body to send
return;
}
// pass the response code
servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());
// send the content to the client
copyResponseEntity(proxyResponse, servletResponse);
} catch (Exception e) {
// abort request
if (proxyRequest instanceof AbortableHttpRequest) {
AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest;
abortableHttpRequest.abort();
}
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
if (e instanceof ServletException) {
throw (ServletException) e;
}
throw new RuntimeException(e);
} finally {
if (proxyResponse != null) {
consumeQuietly(proxyResponse.getEntity());
}
}
}
Aggregations