Example usage for org.apache.commons.httpclient HttpVersion HTTP_1_0

List of usage examples for org.apache.commons.httpclient HttpVersion HTTP_1_0

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpVersion HTTP_1_0.

Prototype

HttpVersion HTTP_1_0

To view the source code for org.apache.commons.httpclient HttpVersion HTTP_1_0.

Click Source Link

Usage

From source file:org.mule.transport.http.transformers.MuleMessageToHttpResponse.java

@Override
public Object transformMessage(MuleMessage msg, String outputEncoding) throws TransformerException {
    Object src = msg.getPayload();

    // Note this transformer excepts Null as we must always return a result
    // from the Http
    // connector if a response transformer is present
    if (src instanceof NullPayload) {
        src = StringUtils.EMPTY;/*from w  w  w .ja  v  a 2s  .c o m*/
    }

    try {
        HttpResponse response;
        if (src instanceof HttpResponse) {
            response = (HttpResponse) src;
        } else {
            response = createResponse(src, outputEncoding, msg);
        }

        // Ensure there's a content type header
        if (!response.containsHeader(HttpConstants.HEADER_CONTENT_TYPE)) {
            response.addHeader(
                    new Header(HttpConstants.HEADER_CONTENT_TYPE, HttpConstants.DEFAULT_CONTENT_TYPE));
        }

        // Ensure there's a content length or transfer encoding header
        if (!response.containsHeader(HttpConstants.HEADER_CONTENT_LENGTH)
                && !response.containsHeader(HttpConstants.HEADER_TRANSFER_ENCODING)) {
            if (response.hasBody()) {
                long len = response.getContentLength();
                if (len < 0) {
                    if (response.getHttpVersion().lessEquals(HttpVersion.HTTP_1_0)) {
                        // Ensure that we convert the payload to an in memory representation
                        // so we don't end up with a chunked response
                        len = msg.getPayloadAsBytes().length;

                        response.setBody(msg);

                        Header header = new Header(HttpConstants.HEADER_CONTENT_LENGTH, Long.toString(len));
                        response.setHeader(header);
                    } else {
                        Header header = new Header(HttpConstants.HEADER_TRANSFER_ENCODING, "chunked");
                        response.addHeader(header);
                    }
                } else {
                    Header header = new Header(HttpConstants.HEADER_CONTENT_LENGTH, Long.toString(len));
                    response.setHeader(header);
                }
            } else {
                Header header = new Header(HttpConstants.HEADER_CONTENT_LENGTH, "0");
                response.addHeader(header);
            }
        }

        // See if the the client explicitly handles connection persistence
        String connHeader = msg.getOutboundProperty(HttpConstants.HEADER_CONNECTION);
        if (connHeader != null) {
            if (connHeader.equalsIgnoreCase("keep-alive")) {
                response.setKeepAlive(true);
            }
            if (connHeader.equalsIgnoreCase("close")) {
                response.setKeepAlive(false);
            }
        }

        final String method = msg.getOutboundProperty(HttpConnector.HTTP_METHOD_PROPERTY);
        if ("HEAD".equalsIgnoreCase(method)) {
            // this is a head request, we don't want to send the actual content
            response.setBody((MuleMessage) null);
        }
        return response;
    } catch (Exception e) {
        throw new TransformerException(this, e);
    }

}

From source file:org.mule.transport.http.transformers.ObjectToHttpClientMethodRequest.java

@Override
public Object transformMessage(MuleMessage msg, String outputEncoding) throws TransformerException {
    String method = detectHttpMethod(msg);
    try {/*from   w  w w  .  j  av a  2 s  . c  o  m*/
        HttpMethod httpMethod;

        if (HttpConstants.METHOD_GET.equals(method)) {
            httpMethod = createGetMethod(msg, outputEncoding);
        } else if (HttpConstants.METHOD_POST.equalsIgnoreCase(method)) {
            httpMethod = createPostMethod(msg, outputEncoding);
        } else if (HttpConstants.METHOD_PUT.equalsIgnoreCase(method)) {
            httpMethod = createPutMethod(msg, outputEncoding);
        } else if (HttpConstants.METHOD_DELETE.equalsIgnoreCase(method)) {
            httpMethod = createDeleteMethod(msg);
        } else if (HttpConstants.METHOD_HEAD.equalsIgnoreCase(method)) {
            httpMethod = createHeadMethod(msg);
        } else if (HttpConstants.METHOD_OPTIONS.equalsIgnoreCase(method)) {
            httpMethod = createOptionsMethod(msg);
        } else if (HttpConstants.METHOD_TRACE.equalsIgnoreCase(method)) {
            httpMethod = createTraceMethod(msg);
        } else if (HttpConstants.METHOD_PATCH.equalsIgnoreCase(method)) {
            httpMethod = createPatchMethod(msg);
        } else {
            throw new TransformerException(HttpMessages.unsupportedMethod(method));
        }

        // Allow the user to set HttpMethodParams as an object on the message
        final HttpMethodParams params = (HttpMethodParams) msg
                .removeProperty(HttpConnector.HTTP_PARAMS_PROPERTY, PropertyScope.OUTBOUND);
        if (params != null) {
            httpMethod.setParams(params);
        } else {
            // TODO we should probably set other properties here
            final String httpVersion = msg.getOutboundProperty(HttpConnector.HTTP_VERSION_PROPERTY,
                    HttpConstants.HTTP11);
            if (HttpConstants.HTTP10.equals(httpVersion)) {
                httpMethod.getParams().setVersion(HttpVersion.HTTP_1_0);
            } else {
                httpMethod.getParams().setVersion(HttpVersion.HTTP_1_1);
            }
        }

        setHeaders(httpMethod, msg);

        return httpMethod;
    } catch (final Exception e) {
        throw new TransformerException(this, e);
    }
}

From source file:org.openlaszlo.data.HTTPDataSource.java

/**
 * @param since last modified time to use
 * @param req//  w w  w. j a v a2  s. c  o m
 * @param url if null, ignored
 * @param redirCount number of redirs we've done
 */
public static HttpData getDataOnce(HttpServletRequest req, HttpServletResponse res, long since, String surl,
        int redirCount, int timeout)
        throws IOException, HttpException, DataSourceException, MalformedURLException {

    HttpMethodBase request = null;
    HostConfiguration hcfg = new HostConfiguration();

    /*
      [todo hqm 2006-02-01] Anyone know why this code was here? It is setting
      the mime type to something which just confuses the DHTML parser.
              
      if (res != null) {
    res.setContentType("application/x-www-form-urlencoded;charset=UTF-8");
    }
    */

    try {

        // TODO: [2002-01-09 bloch] cope with cache-control
        // response headers (no-store, no-cache, must-revalidate, 
        // proxy-revalidate).

        if (surl == null) {
            surl = getURL(req);
        }
        if (surl == null || surl.equals("")) {
            throw new MalformedURLException(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="url is empty or null"
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(),
                            "051018-312"));
        }

        String reqType = "";
        String headers = "";

        if (req != null) {
            reqType = req.getParameter("reqtype");
            headers = req.getParameter("headers");
        }

        boolean isPost = false;
        mLogger.debug("reqtype = " + reqType);

        if (reqType != null && reqType.equals("POST")) {
            request = new LZPostMethod();
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            isPost = true;
            mLogger.debug("setting POST req method");
        } else if (reqType != null && reqType.equals("PUT")) {
            request = new LZPutMethod();
            // todo [hqm 2007] treat PUT like POST? 
            isPost = true;
            mLogger.debug("setting PUT req method");
        } else if (reqType != null && reqType.equals("DELETE")) {
            request = new LZDeleteMethod();
            mLogger.debug("setting DELETE req method");
        } else {
            mLogger.debug("setting GET (default) req method");
            request = new LZGetMethod();
        }

        request.getParams().setVersion(mUseHttp11 ? HttpVersion.HTTP_1_1 : HttpVersion.HTTP_1_0);

        // Proxy the request headers
        if (req != null) {
            LZHttpUtils.proxyRequestHeaders(req, request);
        }

        // Set headers from query string
        if (headers != null && headers.length() > 0) {
            StringTokenizer st = new StringTokenizer(headers, "\n");
            while (st.hasMoreTokens()) {
                String h = st.nextToken();
                int i = h.indexOf(":");
                if (i > -1) {
                    String n = h.substring(0, i);
                    String v = h.substring(i + 2, h.length());
                    request.setRequestHeader(n, v);
                    mLogger.debug(
                            /* (non-Javadoc)
                             * @i18n.test
                             * @org-mes="setting header " + p[0] + "=" + p[1]
                             */
                            org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(),
                                    "051018-359", new Object[] { n, v }));
                }
            }
        }

        mLogger.debug("Parsing url");
        URI uri = LZHttpUtils.newURI(surl);
        try {
            hcfg.setHost(uri);
        } catch (Exception e) {
            throw new MalformedURLException(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="can't form uri from " + p[0]
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-376",
                            new Object[] { surl }));
        }

        // This gets us the url-encoded (escaped) path and query string
        String path = uri.getEscapedPath();
        String query = uri.getEscapedQuery();
        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="encoded path:  " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-389",
                        new Object[] { path }));
        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="encoded query: " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-397",
                        new Object[] { query }));

        // This call takes a decoded (unescaped) path
        request.setPath(path);

        boolean hasQuery = (query != null && query.length() > 0);

        String rawcontent = null;
        // Newer rawpost protocol puts lzpostbody as a separate
        // top level query arg in the request.
        rawcontent = req.getParameter("lzpostbody");

        if (isPost) {
            // Older rawpost protocol put the "lzpostbody" arg
            // embedded in the "url" args's query args
            if (rawcontent == null && hasQuery) {
                rawcontent = findQueryArg("lzpostbody", query);
            }
            if (rawcontent != null) {
                // Get the unescaped query string
                ((EntityEnclosingMethod) request).setRequestEntity(new StringRequestEntity(rawcontent));
            } else if (hasQuery) {
                StringTokenizer st = new StringTokenizer(query, "&");
                while (st.hasMoreTokens()) {
                    String it = st.nextToken();
                    int i = it.indexOf("=");
                    if (i > 0) {
                        String n = it.substring(0, i);
                        String v = it.substring(i + 1, it.length());
                        // POST encodes values during request
                        ((PostMethod) request).addParameter(n, URLDecoder.decode(v, "UTF-8"));
                    } else {
                        mLogger.warn(
                                /* (non-Javadoc)
                                 * @i18n.test
                                 * @org-mes="ignoring bad token (missing '=' char) in query string: " + p[0]
                                 */
                                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(),
                                        "051018-429", new Object[] { it }));
                    }
                }
            }
        } else {
            // This call takes an encoded (escaped) query string
            request.setQueryString(query);
        }

        // Put in the If-Modified-Since headers
        if (since != -1) {
            String lms = LZHttpUtils.getDateString(since);
            request.setRequestHeader(LZHttpUtils.IF_MODIFIED_SINCE, lms);
            mLogger.debug(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="proxying lms: " + p[0]
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-450",
                            new Object[] { lms }));
        }

        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="setting up http client"
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-460"));
        HttpClient htc = null;
        if (mConnectionMgr != null) {
            htc = new HttpClient(mConnectionMgr);
        } else {
            htc = new HttpClient();
        }

        htc.setHostConfiguration(hcfg);

        // This is the data timeout
        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="timeout set to " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-478",
                        new Object[] { timeout }));
        htc.getParams().setSoTimeout(timeout);

        // Set connection timeout the same
        htc.getHttpConnectionManager().getParams().setConnectionTimeout(mConnectionTimeout);

        // Set timeout for getting a connection
        htc.getParams().setConnectionManagerTimeout(mConnectionPoolTimeout);

        // TODO: [2003-03-05 bloch] this should be more configurable (per app?)
        if (!isPost) {
            request.setFollowRedirects(mFollowRedirects > 0);
        }

        long t1 = System.currentTimeMillis();
        mLogger.debug("starting remote request");
        int rc = htc.executeMethod(hcfg, request);
        String status = HttpStatus.getStatusText(rc);
        if (status == null) {
            status = "" + rc;
        }
        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="remote response status: " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-504",
                        new Object[] { status }));

        HttpData data = null;
        if (isRedirect(rc) && mFollowRedirects > redirCount) {
            String loc = request.getResponseHeader("Location").toString();
            String hostURI = loc.substring(loc.indexOf(": ") + 2, loc.length());
            mLogger.info(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="Following URL from redirect: " + p[0]
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-517",
                            new Object[] { hostURI }));
            long t2 = System.currentTimeMillis();
            if (timeout > 0) {
                timeout -= (t2 - t1);
                if (timeout < 0) {
                    throw new InterruptedIOException(
                            /* (non-Javadoc)
                             * @i18n.test
                             * @org-mes=p[0] + " timed out after redirecting to " + p[1]
                             */
                            org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(),
                                    "051018-529", new Object[] { surl, loc }));
                }
            }

            data = getDataOnce(req, res, since, hostURI, redirCount++, timeout);
        } else {
            data = new HttpData(request, rc);
        }

        if (req != null && res != null) {
            // proxy response headers
            LZHttpUtils.proxyResponseHeaders(request, res, req.isSecure());
        }

        return data;

    } catch (ConnectTimeoutException ce) {
        // Transduce to an InterrupedIOException, since lps takes these to be timeouts.
        if (request != null) {
            request.releaseConnection();
        }
        throw new InterruptedIOException(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="connecting to " + p[0] + ":" + p[1] + " timed out beyond " + p[2] + " msecs."
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-557",
                        new Object[] { hcfg.getHost(), hcfg.getPort(), mConnectionTimeout }));
    } catch (HttpRecoverableException hre) {
        if (request != null) {
            request.releaseConnection();
        }
        throw hre;
    } catch (HttpException e) {
        if (request != null) {
            request.releaseConnection();
        }
        throw e;
    } catch (IOException ie) {
        if (request != null) {
            request.releaseConnection();
        }
        throw ie;
    } catch (RuntimeException e) {
        if (request != null) {
            request.releaseConnection();
        }
        throw e;
    }
}

From source file:org.opensaml.ws.soap.client.HTTPSOAPTransportFactory.java

/**
 * Initializes the {@link HttpClient} that will be used by the created {@link HTTPSOAPTransport} built by this
 * factory./*w  w  w.  j a v a 2 s .  c  om*/
 */
protected void initializeHttpClient() {
    HttpConnectionManagerParams connectionParams = new HttpConnectionManagerParams();
    connectionParams.setConnectionTimeout(connectionTimeout);

    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    connectionManager.setParams(connectionParams);

    HttpClientParams clientParams = new HttpClientParams();
    clientParams.setSoTimeout(socketTimeout);
    if (httpVersion == HTTP_VERSION.HTTP1_0) {
        clientParams.setVersion(HttpVersion.HTTP_1_0);
    } else {
        clientParams.setVersion(HttpVersion.HTTP_1_1);
    }

    httpClient = new HttpClient(clientParams, connectionManager);
}

From source file:org.opensaml.ws.transport.http.HttpClientOutTransport.java

public void setVersion(HTTP_VERSION http_version) {
    HttpParams params = postMethod.getParams();

    switch (http_version) {
    case HTTP1_0:
        params.setParameter("http.protocol.version", HttpVersion.HTTP_1_0);
        break;//w w w  .j  a v  a  2  s.  c  o m
    case HTTP1_1:
        params.setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
        break;
    }
}

From source file:org.parosproxy.paros.network.HttpMethodHelper.java

public HttpMethod createRequestMethodNew(HttpRequestHeader header, HttpBody body) throws URIException {
    HttpMethod httpMethod = null;//from  w w  w.  ja v  a2s  .com

    String method = header.getMethod();
    URI uri = header.getURI();
    String version = header.getVersion();

    httpMethod = new GenericMethod(method);

    httpMethod.setURI(uri);
    HttpMethodParams httpParams = httpMethod.getParams();
    // default to use HTTP 1.0
    httpParams.setVersion(HttpVersion.HTTP_1_0);
    if (version.equalsIgnoreCase(HttpHeader.HTTP11)) {
        httpParams.setVersion(HttpVersion.HTTP_1_1);
    }

    // set various headers
    int pos = 0;
    // ZAP: FindBugs fix - always initialise pattern
    Pattern pattern = patternCRLF;
    String delimiter = CRLF;

    String msg = header.getHeadersAsString();
    if ((pos = msg.indexOf(CRLF)) < 0) {
        if ((pos = msg.indexOf(LF)) < 0) {
            delimiter = LF;
            pattern = patternLF;
        }
    } else {
        delimiter = CRLF;
        pattern = patternCRLF;
    }

    String[] split = pattern.split(msg);
    String token = null;
    String name = null;
    String value = null;
    //String host = null;

    for (int i = 0; i < split.length; i++) {
        token = split[i];
        if (token.equals("")) {
            continue;
        }

        if ((pos = token.indexOf(":")) < 0) {
            return null;
        }
        name = token.substring(0, pos).trim();
        value = token.substring(pos + 1).trim();
        httpMethod.addRequestHeader(name, value);

    }

    // set body if post method or put method
    if (body != null && body.length() > 0) {
        EntityEnclosingMethod generic = (EntityEnclosingMethod) httpMethod;
        //         generic.setRequestEntity(new StringRequestEntity(body.toString()));
        generic.setRequestEntity(new ByteArrayRequestEntity(body.getBytes()));

    }

    httpMethod.setFollowRedirects(false);
    return httpMethod;

}

From source file:org.parosproxy.paros.network.HttpMethodHelper.java

public HttpMethod createRequestMethod(HttpRequestHeader header, HttpBody body) throws URIException {
    HttpMethod httpMethod = null;/*w w w  .  j  a v a 2 s .c  o m*/

    String method = header.getMethod();
    URI uri = header.getURI();
    String version = header.getVersion();

    if (method == null || method.trim().length() < 3) {
        throw new URIException("Invalid HTTP method: " + method);
    }

    if (method.equalsIgnoreCase(GET)) {
        //httpMethod = new GetMethod();
        // ZAP: avoid discarding HTTP status code 101 that is used for WebSocket upgrade 
        httpMethod = new ZapGetMethod();
    } else if (method.equalsIgnoreCase(POST)) {
        httpMethod = new ZapPostMethod();
    } else if (method.equalsIgnoreCase(DELETE)) {
        httpMethod = new ZapDeleteMethod();
    } else if (method.equalsIgnoreCase(PUT)) {
        httpMethod = new ZapPutMethod();
    } else if (method.equalsIgnoreCase(HEAD)) {
        httpMethod = new ZapHeadMethod();
    } else if (method.equalsIgnoreCase(OPTIONS)) {
        httpMethod = new ZapOptionsMethod();
    } else if (method.equalsIgnoreCase(TRACE)) {
        httpMethod = new ZapTraceMethod(uri.toString());
    } else {
        httpMethod = new GenericMethod(method);
    }

    try {
        httpMethod.setURI(uri);
    } catch (Exception e1) {
        logger.error(e1.getMessage(), e1);
    }

    HttpMethodParams httpParams = httpMethod.getParams();
    // default to use HTTP 1.0
    httpParams.setVersion(HttpVersion.HTTP_1_0);
    if (version.equalsIgnoreCase(HttpHeader.HTTP11)) {
        httpParams.setVersion(HttpVersion.HTTP_1_1);
    }

    // set various headers
    int pos = 0;
    // ZAP: changed to always use CRLF, like the HttpHeader
    Pattern pattern = patternCRLF;
    String delimiter = header.getLineDelimiter();

    // ZAP: Shouldn't happen as the HttpHeader always uses CRLF
    if (delimiter.equals(LF)) {
        delimiter = LF;
        pattern = patternLF;
    }

    String msg = header.getHeadersAsString();

    String[] split = pattern.split(msg);
    String token = null;
    String name = null;
    String value = null;

    for (int i = 0; i < split.length; i++) {
        token = split[i];
        if (token.equals("")) {
            continue;
        }

        if ((pos = token.indexOf(":")) < 0) {
            return null;
        }
        name = token.substring(0, pos).trim();
        value = token.substring(pos + 1).trim();
        httpMethod.addRequestHeader(name, value);

    }

    // set body if post method or put method
    if (body != null && body.length() > 0 && (httpMethod instanceof EntityEnclosingMethod)) {
        EntityEnclosingMethod post = (EntityEnclosingMethod) httpMethod;
        //         post.setRequestEntity(new StringRequestEntity(body.toString()));
        post.setRequestEntity(new ByteArrayRequestEntity(body.getBytes()));

    }

    httpMethod.setFollowRedirects(false);
    return httpMethod;

}

From source file:org.wso2.carbon.esb.proxyservice.test.proxyservices.ESBJAVA4846HttpProtocolVersionTestCase.java

@Test(groups = "wso2.esb", description = "Sending HTTP1.0 message")
public void sendingHTTP10Message() throws Exception {
    PostMethod post = new PostMethod(getProxyServiceURLHttp("StockQuoteProxyTestHTTPVersion"));
    RequestEntity entity = new StringRequestEntity(getPayload(), "text/xml", "UTF-8");
    post.setRequestEntity(entity);/*w w  w  . j  av a2  s.  c o  m*/
    post.setRequestHeader("SOAPAction", "urn:getQuote");
    HttpMethodParams params = new HttpMethodParams();
    params.setVersion(HttpVersion.HTTP_1_0);
    post.setParams(params);
    HttpClient httpClient = new HttpClient();
    String httpVersion = "";

    try {
        httpClient.executeMethod(post);
        post.getResponseBodyAsString();
        httpVersion = post.getStatusLine().getHttpVersion();
    } finally {
        post.releaseConnection();
    }
    Assert.assertEquals(httpVersion, HttpVersion.HTTP_1_0.toString(), "Http version mismatched");

}