Search in sources :

Example 91 with BasicHttpEntity

use of org.apache.http.entity.BasicHttpEntity in project cloudstack by apache.

the class ClusterServiceServletHttpHandler method writeResponse.

private void writeResponse(HttpResponse response, int statusCode, String content) {
    if (content == null) {
        content = "";
    }
    response.setStatusCode(statusCode);
    final BasicHttpEntity body = new BasicHttpEntity();
    body.setContentType("text/html; charset=UTF-8");
    final byte[] bodyData = content.getBytes();
    body.setContent(new ByteArrayInputStream(bodyData));
    body.setContentLength(bodyData.length);
    response.setEntity(body);
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity)

Example 92 with BasicHttpEntity

use of org.apache.http.entity.BasicHttpEntity in project RoboZombie by sahan.

the class RequestParamEndpointTest method testBufferedHttpEntity.

/**
 * <p>Test for a {@link Request} with a <b>buffered</b> entity.</p>
 *
 * @since 1.3.0
 */
@Test
public final void testBufferedHttpEntity() throws ParseException, IOException {
    Robolectric.getFakeHttpLayer().interceptHttpRequests(false);
    String subpath = "/bufferedhttpentity";
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream inputStream = classLoader.getResourceAsStream("LICENSE.txt");
    InputStream parallelInputStream = classLoader.getResourceAsStream("LICENSE.txt");
    BasicHttpEntity bhe = new BasicHttpEntity();
    bhe.setContent(parallelInputStream);
    stubFor(put(urlEqualTo(subpath)).willReturn(aResponse().withStatus(200)));
    requestEndpoint.bufferedHttpEntity(inputStream);
    verify(putRequestedFor(urlEqualTo(subpath)).withRequestBody(equalTo(EntityUtils.toString(new BufferedHttpEntity(bhe)))));
}
Also used : BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) InputStream(java.io.InputStream) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) Test(org.junit.Test)

Example 93 with BasicHttpEntity

use of org.apache.http.entity.BasicHttpEntity in project FastDev4Android by jiangqqlmj.

the class HurlStack method entityFromConnection.

/**
 * Initializes an {@link HttpEntity} from the given {@link HttpURLConnection}.
 * @param connection
 * @return an HttpEntity populated with data from <code>connection</code>.
 */
private static HttpEntity entityFromConnection(HttpURLConnection connection) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;
    try {
        inputStream = connection.getInputStream();
    } catch (IOException ioe) {
        inputStream = connection.getErrorStream();
    }
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());
    return entity;
}
Also used : InputStream(java.io.InputStream) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) IOException(java.io.IOException)

Example 94 with BasicHttpEntity

use of org.apache.http.entity.BasicHttpEntity in project wso2-synapse by wso2.

the class ClientHandler method processResponse.

/**
 * Perform processing of the received response though Axis2
 *
 * @param conn HTTP connection to be processed
 * @param context HTTP context associated with the connection
 * @param response HTTP response associated with the connection
 */
private void processResponse(final NHttpClientConnection conn, HttpContext context, HttpResponse response) {
    ContentInputBuffer inputBuffer = null;
    MessageContext outMsgContext = (MessageContext) context.getAttribute(OUTGOING_MESSAGE_CONTEXT);
    String endptPrefix = (String) context.getAttribute(NhttpConstants.ENDPOINT_PREFIX);
    String requestMethod = (String) context.getAttribute(NhttpConstants.HTTP_REQ_METHOD);
    int statusCode = response.getStatusLine().getStatusCode();
    boolean expectEntityBody = false;
    if (!"HEAD".equals(requestMethod) && !"OPTIONS".equals(requestMethod) && statusCode >= HttpStatus.SC_OK && statusCode != HttpStatus.SC_NO_CONTENT && statusCode != HttpStatus.SC_NOT_MODIFIED && statusCode != HttpStatus.SC_RESET_CONTENT) {
        expectEntityBody = true;
    } else if (NhttpConstants.HTTP_HEAD.equals(requestMethod)) {
        // When invoking http HEAD request esb set content length as 0 to response header. Since there is no message
        // body content length cannot be calculated inside synapse. Hence additional two headers are added to
        // which contains content length of the backend response and the request method. These headers are removed
        // before submitting the actual response.
        response.addHeader(NhttpConstants.HTTP_REQUEST_METHOD, requestMethod);
        if (response.getFirstHeader(HTTP.CONTENT_LEN) != null) {
            response.addHeader(NhttpConstants.ORIGINAL_CONTENT_LEN, response.getFirstHeader(HTTP.CONTENT_LEN).getValue());
        }
    }
    if (expectEntityBody) {
        inputBuffer = new SharedInputBuffer(cfg.getBufferSize(), conn, allocator);
        context.setAttribute(RESPONSE_SINK_BUFFER, inputBuffer);
        BasicHttpEntity entity = new BasicHttpEntity();
        if (response.getStatusLine().getProtocolVersion().greaterEquals(HttpVersion.HTTP_1_1)) {
            entity.setChunked(true);
        }
        response.setEntity(entity);
        context.setAttribute(ExecutionContext.HTTP_RESPONSE, response);
    } else {
        conn.resetInput();
        conn.resetOutput();
        if (context.getAttribute(NhttpConstants.DISCARD_ON_COMPLETE) != null || !connStrategy.keepAlive(response, context)) {
            try {
                // this is a connection we should not re-use
                connpool.forget(conn);
                shutdownConnection(conn, false, null);
                context.removeAttribute(RESPONSE_SINK_BUFFER);
                context.removeAttribute(REQUEST_SOURCE_BUFFER);
            } catch (Exception ignore) {
            }
        } else {
            connpool.release(conn);
        }
    }
    workerPool.execute(new ClientWorker(cfgCtx, inputBuffer == null ? null : new ContentInputStream(inputBuffer), response, outMsgContext, endptPrefix));
}
Also used : SharedInputBuffer(org.apache.http.nio.util.SharedInputBuffer) ContentInputStream(org.apache.http.nio.entity.ContentInputStream) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) MessageContext(org.apache.axis2.context.MessageContext) URISyntaxException(java.net.URISyntaxException) HttpException(org.apache.http.HttpException) IOException(java.io.IOException) ConnectionClosedException(org.apache.http.ConnectionClosedException) ContentInputBuffer(org.apache.http.nio.util.ContentInputBuffer)

Example 95 with BasicHttpEntity

use of org.apache.http.entity.BasicHttpEntity 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;
}
Also used : BasicHttpRequest(org.apache.http.message.BasicHttpRequest) HttpRequest(org.apache.http.HttpRequest) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URL(java.net.URL) BasicHttpRequest(org.apache.http.message.BasicHttpRequest) Header(org.apache.http.Header) Iterator(java.util.Iterator) Collection(java.util.Collection) HttpException(org.apache.http.HttpException) HttpVersion(org.apache.http.HttpVersion) Map(java.util.Map) BasicHttpEntityEnclosingRequest(org.apache.http.message.BasicHttpEntityEnclosingRequest)

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