Search in sources :

Example 96 with BasicHttpEntity

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();
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) ByteArrayInputStream(java.io.ByteArrayInputStream) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) Map(java.util.Map)

Example 97 with BasicHttpEntity

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);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) HttpContext(org.apache.http.protocol.HttpContext) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) MessageFormatter(org.apache.axis2.transport.MessageFormatter) TreeMap(java.util.TreeMap) DefaultedHttpParams(org.apache.http.params.DefaultedHttpParams) URL(java.net.URL) BasicHttpRequest(org.apache.http.message.BasicHttpRequest) Header(org.apache.http.Header) HttpHost(org.apache.http.HttpHost) MessageContext(org.apache.axis2.context.MessageContext) OMOutputFormat(org.apache.axiom.om.OMOutputFormat) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) BasicHttpEntityEnclosingRequest(org.apache.http.message.BasicHttpEntityEnclosingRequest)

Example 98 with BasicHttpEntity

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);
        }
    }
}
Also used : BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) IOException(java.io.IOException)

Example 99 with BasicHttpEntity

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);
    }
}
Also used : ConfigurationContext(org.apache.axis2.context.ConfigurationContext) HttpResponse(org.apache.http.HttpResponse) HttpInetConnection(org.apache.http.HttpInetConnection) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) InetAddress(java.net.InetAddress) EndpointReference(org.apache.axis2.addressing.EndpointReference)

Example 100 with BasicHttpEntity

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;
    }
}
Also used : BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) IOException(java.io.IOException)

Aggregations

BasicHttpEntity (org.apache.http.entity.BasicHttpEntity)139 ByteArrayInputStream (java.io.ByteArrayInputStream)104 Test (org.junit.Test)89 InputStream (java.io.InputStream)60 IOException (java.io.IOException)24 HttpResponse (org.apache.http.HttpResponse)15 StatusLine (org.apache.http.StatusLine)12 BasicStatusLine (org.apache.http.message.BasicStatusLine)11 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)9 HttpException (org.apache.http.HttpException)8 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)8 HttpContext (org.apache.http.protocol.HttpContext)8 URISyntaxException (java.net.URISyntaxException)7 Map (java.util.Map)7 URI (java.net.URI)6 Header (org.apache.http.Header)6 ProtocolVersion (org.apache.http.ProtocolVersion)6 HttpGet (org.apache.http.client.methods.HttpGet)6 ChunkedInputStream (org.apache.http.impl.io.ChunkedInputStream)6 ContentLengthInputStream (org.apache.http.impl.io.ContentLengthInputStream)6