Example usage for org.apache.http.message BasicHttpRequest BasicHttpRequest

List of usage examples for org.apache.http.message BasicHttpRequest BasicHttpRequest

Introduction

In this page you can find the example usage for org.apache.http.message BasicHttpRequest BasicHttpRequest.

Prototype

public BasicHttpRequest(String str, String str2, ProtocolVersion protocolVersion) 

Source Link

Usage

From source file:org.apache.http.impl.execchain.MainClientExec.java

/**
 * Creates a tunnel to the target server.
 * The connection must be established to the (last) proxy.
 * A CONNECT request for tunnelling through the proxy will
 * be created and sent, the response received and checked.
 * This method does <i>not</i> update the connection with
 * information about the tunnel, that is left to the caller.
 *//* w w  w  .  ja  va  2  s . c o  m*/
private boolean createTunnelToTarget(final AuthState proxyAuthState, final HttpClientConnection managedConn,
        final HttpRoute route, final HttpRequest request, final HttpClientContext context)
        throws HttpException, IOException {

    final RequestConfig config = context.getRequestConfig();
    final int timeout = config.getConnectTimeout();

    final HttpHost target = route.getTargetHost();
    final HttpHost proxy = route.getProxyHost();
    HttpResponse response;

    final String authority = target.toHostString();
    final HttpRequest connect = new BasicHttpRequest("CONNECT", authority, request.getProtocolVersion());

    this.requestExecutor.preProcess(connect, this.proxyHttpProcessor, context);

    for (;;) {
        if (!managedConn.isOpen()) {
            this.connManager.connect(managedConn, route, timeout > 0 ? timeout : 0, context);
        }

        connect.removeHeaders(AUTH.PROXY_AUTH_RESP);
        this.authenticator.generateAuthResponse(connect, proxyAuthState, context);

        response = this.requestExecutor.execute(connect, managedConn, context);

        final int status = response.getStatusLine().getStatusCode();
        if (status < 200) {
            throw new HttpException("Unexpected response to CONNECT request: " + response.getStatusLine());
        }

        if (config.isAuthenticationEnabled()) {
            if (this.authenticator.isAuthenticationRequested(proxy, response, this.proxyAuthStrategy,
                    proxyAuthState, context)) {
                if (this.authenticator.handleAuthChallenge(proxy, response, this.proxyAuthStrategy,
                        proxyAuthState, context)) {
                    // Retry request
                    if (this.reuseStrategy.keepAlive(response, context)) {
                        this.log.debug("Connection kept alive");
                        // Consume response content
                        final HttpEntity entity = response.getEntity();
                        EntityUtils.consume(entity);
                    } else {
                        managedConn.close();
                    }
                } else {
                    break;
                }
            } else {
                break;
            }
        }
    }

    final int status = response.getStatusLine().getStatusCode();

    if (status > 299) {

        // Buffer response content
        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            response.setEntity(new BufferedHttpEntity(entity));
        }

        managedConn.close();
        throw new TunnelRefusedException("CONNECT refused by proxy: " + response.getStatusLine(), response);
    }

    // How to decide on security of the tunnelled connection?
    // The socket factory knows only about the segment to the proxy.
    // Even if that is secure, the hop to the target may be insecure.
    // Leave it to derived classes, consider insecure by default here.
    return false;
}

From source file:org.apache.http.impl.nio.client.DefaultAsyncRequestDirector.java

private HttpRequest createConnectRequest(final HttpRoute route) {
    // see RFC 2817, section 5.2 and
    // INTERNET-DRAFT: Tunneling TCP based protocols through
    // Web proxy servers
    final HttpHost target = route.getTargetHost();
    final String host = target.getHostName();
    int port = target.getPort();
    if (port < 0) {
        final AsyncSchemeRegistry registry = getSchemeRegistry(this.localContext);
        final AsyncScheme scheme = registry.getScheme(target.getSchemeName());
        port = scheme.getDefaultPort();/*from   w  w w  . ja v  a 2s  .  c o  m*/
    }
    final StringBuilder buffer = new StringBuilder(host.length() + 6);
    buffer.append(host);
    buffer.append(':');
    buffer.append(Integer.toString(port));
    final ProtocolVersion ver = HttpProtocolParams.getVersion(this.params);
    final HttpRequest req = new BasicHttpRequest("CONNECT", buffer.toString(), ver);
    return req;
}

From source file:org.apache.http.impl.nio.client.MainClientExec.java

private HttpRequest createConnectRequest(final HttpRoute route, final InternalState state)
        throws IOException, HttpException {
    // see RFC 2817, section 5.2 and
    // INTERNET-DRAFT: Tunneling TCP based protocols through
    // Web proxy servers
    final HttpHost target = route.getTargetHost();
    final String host = target.getHostName();
    final int port = target.getPort();
    final StringBuilder buffer = new StringBuilder(host.length() + 6);
    buffer.append(host);//from   ww  w .  j  av a  2 s .c om
    buffer.append(':');
    buffer.append(Integer.toString(port));
    final HttpRequest request = new BasicHttpRequest("CONNECT", buffer.toString(), HttpVersion.HTTP_1_1);
    final HttpClientContext localContext = state.getLocalContext();
    this.proxyHttpProcessor.process(request, localContext);
    return request;
}

From source file:org.apache.synapse.transport.passthru.TargetRequest.java

public void start(NHttpClientConnection conn) throws IOException, HttpException {
    if (pipe != null) {
        TargetContext.get(conn).setWriter(pipe);
    }/*from  w  w w.j ava 2 s .com*/

    String path = fullUrl || (route.getProxyHost() != null && !route.isTunnelled()) ? url.toString()
            : url.getPath() + (url.getQuery() != null ? "?" + url.getQuery() : "");

    long contentLength = -1;
    String contentLengthHeader = null;
    if (headers.get(HTTP.CONTENT_LEN) != null && headers.get(HTTP.CONTENT_LEN).size() > 0) {
        contentLengthHeader = headers.get(HTTP.CONTENT_LEN).first();
    }

    if (contentLengthHeader != null) {
        contentLength = Integer.parseInt(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 ((("GET").equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD)))
            || (("DELETE").equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD)))) {
        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 (!trpContentType.contains(PassThroughConstants.CONTENT_TYPE_MULTIPART_RELATED)) {
                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 > 0) {
                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, TreeSet<String>>> entries = headers.entrySet();
    for (Map.Entry<String, TreeSet<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();
        }
        if (soapAction == null) {
            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()));

    //Chucking is not performed for request has "http 1.0" and "GET" http method
    if (!((request.getProtocolVersion().equals(HttpVersion.HTTP_1_0))
            || (("GET").equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD)))
            || (("DELETE").equals(requestMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD))))) {
        this.processChunking(conn, requestMsgCtx);
    }

    if (!keepAlive) {
        request.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
    }

    // Pre-process HTTP request
    conn.getContext().setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    conn.getContext().setAttribute(ExecutionContext.HTTP_TARGET_HOST, new HttpHost(url.getHost(), port));
    conn.getContext().setAttribute(ExecutionContext.HTTP_REQUEST, request);

    // start the request
    targetConfiguration.getHttpProcessor().process(request, conn.getContext());

    if (targetConfiguration.getProxyAuthenticator() != null && route.getProxyHost() != null
            && !route.isTunnelled()) {
        targetConfiguration.getProxyAuthenticator().authenticatePreemptively(request, conn.getContext());
    }

    conn.submitRequest(request);

    if (hasEntityBody) {
        TargetContext.updateState(conn, ProtocolState.REQUEST_HEAD);
    } else {
        TargetContext.updateState(conn, ProtocolState.REQUEST_DONE);
    }
}