Package org.apache.commons.httpclient

Examples of org.apache.commons.httpclient.HttpMethod


    @Test
    public void testShouldBeAbleToAccessServletAndEjb() throws Exception {
        String[] sessionResult = new String[2];
        for (int i = 0; i < sessionResult.length; i++) {
            HttpClient client = new HttpClient();
            HttpMethod get = new GetMethod(TEST_SESSION_URL);
            String[] contents = new String[2];
            try {
                for (int j = 0; j < contents.length; j++) {
                    int out = client.executeMethod(get);
                    if (out != 200) {
                        throw new RuntimeException("get " + TEST_SESSION_URL + " returned " + out);
                    }
                    contents[j] = get.getResponseBodyAsString();
                }

                assertEquals(contents[0], contents[1]);
            } finally {
                get.releaseConnection();
            }
            sessionResult[i] = contents[0];
        }

        assertNotSame(sessionResult[0], sessionResult[1]);
View Full Code Here


    @Ignore
    public void testShouldBeAbleToAccessServletAndEjb() throws Exception {
        String[] sessionResult = new String[2];
        for (int i = 0; i < sessionResult.length; i++) {
            HttpClient client = new HttpClient();
            HttpMethod get = new GetMethod(TEST_SESSION_URL);
            String[] contents = new String[2];
            try {
                for (int j = 0; j < contents.length; j++) {
                    int out = client.executeMethod(get);
                    if (out != 200) {
                        throw new RuntimeException("get " + TEST_SESSION_URL + " returned " + out);
                    }
                    contents[j] = get.getResponseBodyAsString();
                }

                assertEquals(contents[0], contents[1]);
            } finally {
                get.releaseConnection();
            }
            sessionResult[i] = contents[0];
        }

        assertNotSame(sessionResult[0], sessionResult[1]);
View Full Code Here

        {
            if ( GET.equals( findMethodType() ) )
            {
                try
                {
                    final HttpMethod head = createHeadMethod( m_uri );
                    executeMethod( head );
                    head.releaseConnection();
                    return;
                }
                catch ( final IOException e )
                {
                    if ( getLogger().isDebugEnabled() )
View Full Code Here

     * @throws SourceNotFoundException if the source doesn't exist.
     */
    public InputStream getInputStream()
        throws IOException, SourceNotFoundException
    {
        final HttpMethod method = getMethod();
        final int response = executeMethod( method );
        m_dataValid = true;

        // throw SourceNotFoundException - according to Source API we
        // need to throw this if the source doesn't exist.
        if ( !exists() )
        {
            final StringBuffer error = new StringBuffer();
            error.append( "Unable to retrieve URI: " );
            error.append( m_uri );
            error.append( " (" );
            error.append( response );
            error.append( ")" );

            throw new SourceNotFoundException( error.toString() );
        }

        return method.getResponseBodyAsStream();
    }
View Full Code Here

         * @exception IOException if an error occurs
         */
        private void upload()
            throws IOException
        {
            HttpMethod uploader = null;

            if ( m_logger.isDebugEnabled() )
            {
                m_logger.debug( "Stream closed, writing data to " + m_uri );
            }

            try
            {
                uploader = createPutMethod( m_uri, m_file );
                final int response = executeMethod( uploader );

                if ( !successfulUpload( response ) )
                {
                    throw new SourceException(
                        "Write to " + m_uri + " failed (" + response + ")"
                    );
                }

                if ( m_logger.isDebugEnabled() )
                {
                    m_logger.debug(
                        "Write to " + m_uri + " succeeded (" + response + ")"
                    );
                }
            }
            finally
            {
                if ( uploader != null )
                {
                    uploader.releaseConnection();
                }
            }
        }
View Full Code Here

  }

  private static int httpNotification(String uri) throws IOException {
    URI url = new URI(uri, false);
    HttpClient m_client = new HttpClient();
    HttpMethod method = new GetMethod(url.getEscapedURI());
    method.setRequestHeader("Accept", "*/*");
    return m_client.executeMethod(method);
  }
View Full Code Here

        HostConfiguration hc = new HostConfiguration();
        hc.setHost(url);
        client.setHostConfiguration(hc);
       
        //TODO support other methods
        HttpMethod method = new GetMethod(url.getPathQuery());
        Header[] headers = request.getHeaders();
        for (int i=0; i<headers.length; i++) {
            method.addRequestHeader(headers[i]);
        }
        if (method instanceof EntityEnclosingMethod) {
            EntityEnclosingMethod emethod = (EntityEnclosingMethod) method;
            emethod.setRequestEntity(
                new InputStreamRequestEntity(conn.getInputStream()));
        }
        client.executeMethod(method);

       
        Header[] rheaders = method.getResponseHeaders();
        InputStream targetIn = method.getResponseBodyAsStream();
        ResponseWriter out = conn.getWriter();
        out.println(method.getStatusLine().toString());
        for (int i=0; i<rheaders.length; i++) {
            out.print(rheaders[i].toExternalForm());
        }
        if (rheaders.length > 0) out.println();
        out.flush();
View Full Code Here

public class NettyHttpMapHeadersFalseTest extends BaseNettyTest {

    @Test
    public void testHttpHeaderCase() throws Exception {
        HttpClient client = new HttpClient();
        HttpMethod method = new PostMethod("http://localhost:" + getPort() + "/myapp/mytest");

        method.setRequestHeader("clientHeader", "fooBAR");
        method.setRequestHeader("OTHER", "123");
        method.setRequestHeader("beer", "Carlsberg");

        client.executeMethod(method);

        assertEquals("Bye World", method.getResponseBodyAsString());
        assertEquals("aBc123", method.getResponseHeader("MyCaseHeader").getValue());
        assertEquals("456DEf", method.getResponseHeader("otherCaseHeader").getValue());
    }
View Full Code Here

            }

            URL url = createURL(request);

            // Forward "InputStream", Parameters, QueryString to Servlet
            HttpMethod httpMethod = null;

            if (submitMethod.equals("POST")) {
                httpMethod = new PostMethod();

                Enumeration params = request.getParameterNames();

                while (params.hasMoreElements()) {
                    String paramName = (String) params.nextElement();
                    String[] paramValues = request.getParameterValues(paramName);

                    for (int i = 0; i < paramValues.length; i++) {
                        ((PostMethod) httpMethod).setParameter(paramName, paramValues[i]);
                    }
                }
            } else if (submitMethod.equals("GET")) {
                httpMethod = new GetMethod();
                httpMethod.setQueryString(request.getQueryString());
            }

            // Copy/clone Cookies
            Cookie[] cookies = request.getCookies();
            org.apache.commons.httpclient.Cookie[] transferedCookies = null;

            if (cookies != null) {
                transferedCookies = new org.apache.commons.httpclient.Cookie[cookies.length];

                for (int i = 0; i < cookies.length; i++) {
                    boolean secure = false; // http: false, https: true
                    transferedCookies[i] = new org.apache.commons.httpclient.Cookie(url.getHost(),
                            cookies[i].getName(), cookies[i].getValue(), url.getFile(), null,
                            secure);
                }
            }

            // Initialize HttpClient
            HttpClient httpClient = new HttpClient();

            // Set cookies
            if ((transferedCookies != null) && (transferedCookies.length > 0)) {
                HttpState httpState = new HttpState();
                httpState.addCookies(transferedCookies);
                httpClient.setState(httpState);
            }

            // DEBUG cookies
            // Send request to servlet
            httpMethod.setRequestHeader("Content-type", "text/plain");
            httpMethod.setPath(url.getPath());

            // FIXME
            for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) {
                String name = (String) e.nextElement();
                httpMethod.addRequestHeader(name, request.getHeader(name));
                log.debug("Header Name=" + name + "value=" + request.getHeader(name));
            }

            HostConfiguration hostConfiguration = new HostConfiguration();
            hostConfiguration.setHost(url.getHost(), url.getPort(), url.getProtocol());

            log.debug("\n----------------------------------------------------------------"
                    + "\n- Starting session at URI: " + url + "\n- Host:                    "
                    + url.getHost() + "\n- Port:                    " + url.getPort()
                    + "\n----------------------------------------------------------------");

            if (trustStore != null) {
              System.setProperty("javax.net.ssl.trustStore", trustStore);
            }           
            if (trustStorePassword != null) {
              System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);    
            }

            int result = httpClient.executeMethod(hostConfiguration, httpMethod);

            log.debug("\n----------------------------------------------------------------"
                    + "\n- Result:                    " + result
                    + "\n----------------------------------------------------------------");

            // Handle GZIP Content-Encoding
            InputStream is = null;
            Header contentEncodingHeader = httpMethod.getResponseHeader("Content-Encoding");
            if (contentEncodingHeader != null && contentEncodingHeader.getValue().equalsIgnoreCase("gzip")) {
               is = new GZIPInputStream(httpMethod.getResponseBodyAsStream());
               log.debug("The content type is gzip.");
            } else {
                is = httpMethod.getResponseBodyAsStream();
            }

            // Return XML
            InputSource input = new InputSource(is);
            parser = (SAXParser) this.manager.lookup(SAXParser.ROLE);
            parser.parse(input, this.xmlConsumer);
            httpMethod.releaseConnection();
        } catch (SAXException e) {
            throw e;
        } catch (Exception e) {
            getLogger().error("Generation failed: ", e);
            throw new SAXException(e);
View Full Code Here

        super(endpoint);
        httpClient = endpoint.createHttpClient();
    }

    public void process(Exchange exchange) throws Exception {
        HttpMethod method = createMethod(exchange);
        Message in = exchange.getIn();
        HeaderFilterStrategy strategy = ((HttpEndpoint)getEndpoint()).getHeaderFilterStrategy();

        // propagate headers as HTTP headers
        for (String headerName : in.getHeaders().keySet()) {
            String headerValue = in.getHeader(headerName, String.class);
            if (strategy != null && !strategy.applyFilterToCamelHeaders(headerName, headerValue)) {
                method.addRequestHeader(headerName, headerValue);
            }
        }

        // lets store the result in the output message.
        try {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Executing http " + method.getName() + " method: " + method.getURI().toString());
            }
            int responseCode = executeMethod(method);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Http responseCode: " + responseCode);
            }

            if (responseCode >= 100 && responseCode < 300) {
                Message answer = exchange.getOut(true);

                answer.setHeaders(in.getHeaders());
                answer.setHeader(HTTP_RESPONSE_CODE, responseCode);
                answer.setBody(extractResponseBody(method));

                // propagate HTTP response headers
                Header[] headers = method.getResponseHeaders();
                for (Header header : headers) {
                    String name = header.getName();
                    String value = header.getValue();
                    if (strategy != null && !strategy.applyFilterToExternalHeaders(name, value)) {
                        answer.setHeader(name, value);
                    }
                }
            } else {
                HttpOperationFailedException exception = null;
                if (responseCode < 400 && responseCode >= 300) {
                    String redirectLocation;
                    Header locationHeader = method.getResponseHeader("location");
                    if (locationHeader != null) {
                        redirectLocation = locationHeader.getValue();
                        exception = new HttpOperationFailedException(responseCode, method.getStatusLine(), redirectLocation);
                    }
                } else {
                    exception = new HttpOperationFailedException(responseCode, method.getStatusLine());
                }

                throw exception;
            }

        } finally {
            method.releaseConnection();
        }
    }
View Full Code Here

TOP

Related Classes of org.apache.commons.httpclient.HttpMethod

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.