use of org.apache.http.entity.BasicHttpEntity in project wso2-synapse by wso2.
the class BasicHttpClient method doPost.
/**
* Make a HTTP POST request on the specified URL.
*
* @param url A valid HTTP URL
* @param payload An array of bytes to be posted to the URL (message body)
* @param contentType Content type of the message body
* @param headers A map of HTTP headers to be set on the outgoing request
* @return A HttpResponse object
* @throws Exception If an error occurs while making the HTTP call
*/
public HttpResponse doPost(String url, byte[] payload, String contentType, Map<String, String> headers) throws Exception {
CloseableHttpClient client = HttpClientBuilder.create().build();
try {
HttpPost post = new HttpPost(url);
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
post.setHeader(entry.getKey(), entry.getValue());
}
}
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContentType(contentType);
entity.setContent(new ByteArrayInputStream(payload));
post.setEntity(entity);
return new HttpResponse(client.execute(post));
} finally {
client.close();
}
}
use of org.apache.http.entity.BasicHttpEntity 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.entity.BasicHttpEntity in project wso2-synapse by wso2.
the class TargetResponse method start.
/**
* Starts the response
* @param conn the client connection
*/
public void start(NHttpClientConnection conn) {
TargetContext.updateState(conn, ProtocolState.RESPONSE_HEAD);
if (expectResponseBody) {
pipe = new Pipe(conn, targetConfiguration.getBufferFactory().getBuffer(), "target", targetConfiguration);
TargetContext.get(conn).setReader(pipe);
BasicHttpEntity entity = new BasicHttpEntity();
if (response.getStatusLine().getProtocolVersion().greaterEquals(HttpVersion.HTTP_1_1)) {
entity.setChunked(true);
}
response.setEntity(entity);
} else {
if (!connStrategy.keepAlive(response, conn.getContext()) || forceShutdownConnectionOnComplete) {
try {
// this is a connection we should not re-use
TargetContext.updateState(conn, ProtocolState.CLOSING);
targetConfiguration.getConnections().shutdownConnection(conn, forceShutdownConnectionOnComplete);
} catch (Exception ignore) {
}
} else {
// Complete the state transition
TargetContext.updateState(conn, ProtocolState.RESPONSE_DONE);
targetConfiguration.getConnections().releaseConnection(conn);
}
}
}
use of org.apache.http.entity.BasicHttpEntity in project wso2-synapse by wso2.
the class ServerWorker method processHttpRequestUri.
/**
* Get Uri of underlying SourceRequest and calculate service prefix and add to message context
* create response buffers for HTTP GET, DELETE, OPTION and HEAD methods
* @param msgContext Axis2MessageContext of the request
* @param method HTTP Method of the request
*/
public void processHttpRequestUri(MessageContext msgContext, String method) {
String servicePrefixIndex = "://";
ConfigurationContext cfgCtx = sourceConfiguration.getConfigurationContext();
msgContext.setProperty(Constants.Configuration.HTTP_METHOD, request.getMethod());
// String uri = request.getUri();
String oriUri = request.getUri();
String restUrlPostfix = NhttpUtil.getRestUrlPostfix(oriUri, cfgCtx.getServicePath());
String servicePrefix = oriUri.substring(0, oriUri.indexOf(restUrlPostfix));
if (servicePrefix.indexOf(servicePrefixIndex) == -1) {
HttpInetConnection inetConn = (HttpInetConnection) request.getConnection();
InetAddress localAddr = inetConn.getLocalAddress();
if (localAddr != null) {
servicePrefix = sourceConfiguration.getScheme().getName() + servicePrefixIndex + localAddr.getHostAddress() + ":" + inetConn.getLocalPort() + servicePrefix;
}
}
msgContext.setProperty(PassThroughConstants.SERVICE_PREFIX, servicePrefix);
msgContext.setTo(new EndpointReference(restUrlPostfix));
msgContext.setProperty(PassThroughConstants.REST_URL_POSTFIX, restUrlPostfix);
if (PassThroughConstants.HTTP_GET.equals(method) || PassThroughConstants.HTTP_HEAD.equals(method) || PassThroughConstants.HTTP_OPTIONS.equals(method)) {
HttpResponse response = sourceConfiguration.getResponseFactory().newHttpResponse(request.getVersion(), HttpStatus.SC_OK, request.getConnection().getContext());
// create a basic HttpEntity using the source channel of the response pipe
BasicHttpEntity entity = new BasicHttpEntity();
if (request.getVersion().greaterEquals(HttpVersion.HTTP_1_1)) {
entity.setChunked(true);
}
response.setEntity(entity);
httpGetRequestProcessor.process(request.getRequest(), response, msgContext, request.getConnection(), os, isRestDispatching);
}
}
use of org.apache.http.entity.BasicHttpEntity in project wso2-synapse by wso2.
the class ServerHandler method commitResponse.
/**
* Commit the response to the connection. Processes the response through the configured
* HttpProcessor and submits it to be sent out. Re-Throws exceptions, after closing connections
* @param conn the connection being processed
* @param response the response to commit over the connection
* @throws IOException if an IO error occurs while sending the response
* @throws HttpException if a HTTP protocol violation occurs while sending the response
*/
public void commitResponse(final NHttpServerConnection conn, final HttpResponse response) throws IOException, HttpException {
try {
BasicHttpEntity entity = (BasicHttpEntity) response.getEntity();
Header[] headers = response.getAllHeaders();
int contentLength = -1;
if (canResponseHaveBody(response, conn)) {
if (entity == null) {
entity = new BasicHttpEntity();
}
for (Header header : headers) {
if (header.getName().equals(HTTP.CONTENT_LEN) && Integer.parseInt(header.getValue()) > 0) {
contentLength = Integer.parseInt(header.getValue());
response.removeHeader(header);
}
}
if (contentLength != -1) {
entity.setChunked(false);
entity.setContentLength(contentLength);
} else {
entity.setChunked(true);
}
} else {
if (entity != null) {
entity.setChunked(false);
entity.setContentLength(contentLength);
}
}
response.setEntity(entity);
conn.suspendInput();
HttpContext context = conn.getContext();
httpProcessor.process(response, context);
conn.getContext().setAttribute(NhttpConstants.RES_TO_CLIENT_WRITE_START_TIME, System.currentTimeMillis());
conn.submitResponse(response);
} catch (HttpException e) {
shutdownConnection(conn, true, e.getMessage());
throw e;
} catch (IOException e) {
shutdownConnection(conn, true, e.getMessage());
throw e;
}
}
Aggregations