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

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

Introduction

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

Prototype

HttpVersion HTTP_1_1

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

Click Source Link

Usage

From source file:org.carrot2.util.httpclient.HttpUtils.java

/**
 * Opens a HTTP/1.1 connection to the given URL using the GET method, decompresses
 * compressed response streams, if supported by the server.
 * //from   w  w w  .j  a  v  a  2 s .co m
 * @param url The URL to open. The URL must be properly escaped, this method will
 *            <b>not</b> perform any escaping.
 * @param params Query string parameters to be attached to the url.
 * @param headers Any extra HTTP headers to add to the request.
 * @param user if not <code>null</code>, the user name to send during Basic
 *            Authentication
 * @param password if not <code>null</code>, the password name to send during Basic
 *            Authentication
 * @return The {@link HttpUtils.Response} object. Note that entire payload is read and
 *         buffered so that the HTTP connection can be closed when leaving this
 *         method.
 */
public static Response doGET(String url, Collection<NameValuePair> params, Collection<Header> headers,
        String user, String password, int timeout) throws HttpException, IOException {
    final HttpClient client = HttpClientFactory.getTimeoutingClient(timeout);
    client.getParams().setVersion(HttpVersion.HTTP_1_1);

    final GetMethod request = new GetMethod();

    if (user != null && password != null) {
        client.getState().setCredentials(new AuthScope(null, 80, null),
                new UsernamePasswordCredentials(user, password));
        request.setDoAuthentication(true);
    }

    final Response response = new Response();
    try {
        request.setURI(new URI(url, true));

        if (params != null) {
            request.setQueryString(params.toArray(new NameValuePair[params.size()]));
        }

        request.setRequestHeader(HttpHeaders.URL_ENCODED);
        request.setRequestHeader(HttpHeaders.GZIP_ENCODING);
        if (headers != null) {
            for (Header header : headers)
                request.setRequestHeader(header);
        }

        org.slf4j.LoggerFactory.getLogger(HttpUtils.class).debug("GET: " + request.getURI());

        final int statusCode = client.executeMethod(request);
        response.status = statusCode;

        InputStream stream = request.getResponseBodyAsStream();
        final Header encoded = request.getResponseHeader("Content-Encoding");
        if (encoded != null && "gzip".equalsIgnoreCase(encoded.getValue())) {
            stream = new GZIPInputStream(stream);
            response.compression = COMPRESSION_GZIP;
        } else {
            response.compression = COMPRESSION_NONE;
        }

        final Header[] respHeaders = request.getResponseHeaders();
        response.headers = new String[respHeaders.length][];
        for (int i = 0; i < respHeaders.length; i++) {
            response.headers[i] = new String[] { respHeaders[i].getName(), respHeaders[i].getValue() };
        }

        response.payload = StreamUtils.readFullyAndClose(stream);
        return response;
    } finally {
        request.releaseConnection();
    }
}

From source file:org.cbarrett.lcbo.LCBOClient.java

public LCBOClient(RestTemplate restTemplate) {
    this.restTemplate = restTemplate;

    CommonsClientHttpRequestFactory factory = (CommonsClientHttpRequestFactory) restTemplate
            .getRequestFactory();/*  w  w  w  . j  av a2 s . c  om*/
    HttpClient client = factory.getHttpClient();

    client.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    client.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
    client.getParams().setParameter("http.protocol.content-charset", "UTF-8");
    client.getParams().setParameter("http.useragent", "lcbo-tools");
}

From source file:org.eclipse.ecf.tests.remoteservice.rest.service.SimpleRestService.java

protected void hookResponse(SimpleHttpServerConnection conn, String body) throws IOException {
    SimpleResponse res = new SimpleResponse();
    res.setStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK);
    res.setBodyString(body);/*from www.  j  av  a  2s  . c  o m*/
    conn.setKeepAlive(false);
    conn.writeResponse(res);
}

From source file:org.eclipse.smila.connectivity.framework.crawler.web.http.HttpResponse.java

/**
 * Sets the http parameters.//from ww w.ja  v a  2s.c  o  m
 * 
 * @param http
 *          the http
 * @param httpMethod
 *          the http method
 */
private void setHttpParameters(HttpBase http, HttpMethodBase httpMethod) {
    httpMethod.setFollowRedirects(false);
    httpMethod.setRequestHeader("User-Agent", http.getUserAgent());
    httpMethod.setRequestHeader("Referer", http.getReferer());

    httpMethod.setDoAuthentication(true);

    for (Header header : http.getHeaders()) {
        httpMethod.addRequestHeader(header);
    }

    final HttpMethodParams params = httpMethod.getParams();
    if (http.getUseHttp11()) {
        params.setVersion(HttpVersion.HTTP_1_1);
    } else {
        params.setVersion(HttpVersion.HTTP_1_0);
    }
    params.makeLenient();
    params.setContentCharset("UTF-8");

    if (http.isCookiesEnabled()) {
        params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    } else {
        params.setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    }
    params.setBooleanParameter(HttpMethodParams.SINGLE_COOKIE_HEADER, true);
    // the default is to retry 3 times; if
    // the request body was sent the method is not retried, so there is
    // little danger in retrying
    // retries are handled on the higher level
    params.setParameter(HttpMethodParams.RETRY_HANDLER, null);
}

From source file:org.exoplatform.services.common.HttpClientImpl.java

private void setHost(String protocol, String host, int port) throws Exception {
    MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager();
    HttpConnectionManagerParams para = new HttpConnectionManagerParams();
    para.setConnectionTimeout(HTTP_TIMEOUT);
    para.setDefaultMaxConnectionsPerHost(10);
    para.setMaxTotalConnections(20);/* ww w  .j av a  2 s . c om*/
    para.setStaleCheckingEnabled(true);
    manager.setParams(para);
    http = new HttpClient(manager);
    http.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
    http.getParams().setParameter("http.socket.timeout", new Integer(HTTP_TIMEOUT));
    http.getParams().setParameter("http.protocol.content-charset", "UTF-8");
    http.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    http.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    if (port < 0)
        port = 80;
    HostConfiguration hostConfig = http.getHostConfiguration();
    hostConfig.setHost(host, port, protocol);

    String proxyHost = System.getProperty("httpclient.proxy.host");
    if (proxyHost == null || proxyHost.trim().length() < 1)
        return;
    String proxyPort = System.getProperty("httpclient.proxy.port");
    hostConfig.setProxy(proxyHost, Integer.parseInt(proxyPort));

    String username = System.getProperty("httpclient.proxy.username");
    String password = System.getProperty("httpclient.proxy.password");
    String ntlmHost = System.getProperty("httpclient.proxy.ntlm.host");
    String ntlmDomain = System.getProperty("httpclient.proxy.ntlm.domain");

    Credentials ntCredentials;
    if (ntlmHost == null || ntlmDomain == null) {
        ntCredentials = new UsernamePasswordCredentials(username, password);
    } else {
        ntCredentials = new NTCredentials(username, password, ntlmHost, ntlmDomain);
    }
    http.getState().setProxyCredentials(AuthScope.ANY, ntCredentials);
}

From source file:org.mule.transport.http.functional.HttpContinueFunctionalTestCase.java

@Test
public void testSendWithContinue() throws Exception {
    stopWatch = new StopWatch();
    MuleClient client = new MuleClient(muleContext);

    //Need to use Http1.1 for Expect: Continue
    HttpClientParams params = new HttpClientParams();
    params.setVersion(HttpVersion.HTTP_1_1);
    params.setBooleanParameter(HttpClientParams.USE_EXPECT_CONTINUE, true);

    Map<String, Object> props = new HashMap<String, Object>();
    props.put(HttpConnector.HTTP_PARAMS_PROPERTY, params);

    stopWatch.start();/*www  .  j  a v a 2  s . com*/
    MuleMessage result = client.send("clientEndpoint", TEST_MESSAGE, props);
    stopWatch.stop();

    assertNotNull(result);
    assertEquals(TEST_MESSAGE + " Received", result.getPayloadAsString());

    if (stopWatch.getTime() > DEFAULT_HTTP_CLIENT_CONTINUE_WAIT) {
        fail("Server did not handle Expect=100-continue header properly,");
    }
}

From source file:org.mule.transport.http.functional.HttpKeepAliveFunctionalTestCase.java

@Override
protected void doSetUp() throws Exception {
    super.doSetUp();

    http10Client = setupHttpClient(HttpVersion.HTTP_1_0);
    http11Client = setupHttpClient(HttpVersion.HTTP_1_1);
    client = new MuleClient(muleContext);
}

From source file:org.mule.transport.http.HttpMessageProcessTemplate.java

private void sendExpect100(HttpRequest request) throws MuleException, IOException {
    RequestLine requestLine = request.getRequestLine();

    // respond with status code 100, for Expect handshake
    // according to rfc 2616 and http 1.1
    // the processing will continue and the request will be fully
    // read immediately after
    HttpVersion requestVersion = requestLine.getHttpVersion();
    if (HttpVersion.HTTP_1_1.equals(requestVersion)) {
        Header expectHeader = request.getFirstHeader(HttpConstants.HEADER_EXPECT);
        if (expectHeader != null) {
            String expectHeaderValue = expectHeader.getValue();
            if (HttpConstants.HEADER_EXPECT_CONTINUE_REQUEST_VALUE.equals(expectHeaderValue)) {
                HttpResponse expected = new HttpResponse();
                expected.setStatusLine(requestLine.getHttpVersion(), HttpConstants.SC_CONTINUE);
                final DefaultMuleEvent event = new DefaultMuleEvent(
                        new DefaultMuleMessage(expected, getMuleContext()), getInboundEndpoint(),
                        getFlowConstruct());
                RequestContext.setEvent(event);
                httpServerConnection.writeResponse(transformResponse(expected));
            }/*from www  . j av a2 s  .c  o  m*/
        }
    }
}

From source file:org.mule.transport.http.HttpMuleMessageFactoryTestCase.java

@Test
public void testHttpMethodGet() throws Exception {
    InputStream body = new ByteArrayInputStream("/services/Echo".getBytes());
    HttpMethod method = createMockHttpMethod(HttpConstants.METHOD_GET, body, URI, HEADERS);

    MuleMessageFactory factory = createMuleMessageFactory();
    MuleMessage message = factory.create(method, encoding);
    assertNotNull(message);/* w  ww. ja  v a 2  s  .  co m*/
    assertEquals("/services/Echo", message.getPayloadAsString());
    assertEquals(HttpConstants.METHOD_GET, message.getInboundProperty(HttpConnector.HTTP_METHOD_PROPERTY));
    assertEquals(HttpVersion.HTTP_1_1.toString(),
            message.getInboundProperty(HttpConnector.HTTP_VERSION_PROPERTY));
    assertEquals("200", message.getInboundProperty(HttpConnector.HTTP_STATUS_PROPERTY));
}

From source file:org.mule.transport.http.HttpMuleMessageFactoryTestCase.java

@Test
public void testHttpMethodPost() throws Exception {
    InputStream body = new ByteArrayInputStream(TEST_MESSAGE.getBytes());
    HttpMethod method = createMockHttpMethod(HttpConstants.METHOD_POST, body, "http://localhost/services/Echo",
            HEADERS);/*from   www  .j  av a 2  s.  co  m*/

    MuleMessageFactory factory = createMuleMessageFactory();
    MuleMessage message = factory.create(method, encoding);
    assertNotNull(message);
    assertEquals(TEST_MESSAGE, message.getPayloadAsString());
    assertEquals(HttpConstants.METHOD_POST, message.getInboundProperty(HttpConnector.HTTP_METHOD_PROPERTY));
    assertEquals(HttpVersion.HTTP_1_1.toString(),
            message.getInboundProperty(HttpConnector.HTTP_VERSION_PROPERTY));
    assertEquals("200", message.getInboundProperty(HttpConnector.HTTP_STATUS_PROPERTY));
}