Package org.apache.commons.httpclient

Examples of org.apache.commons.httpclient.HttpMethodBase


    }

    private void testDefaultRetryHandler(final String method)
        throws Exception
    {
        final HttpMethodBase httpMethodBase = executeTest(method, null) ;
        final HttpMethodParams params = httpMethodBase.getParams() ;
        final Object handler = params.getParameter(HttpMethodParams.RETRY_HANDLER) ;
        assertNotNull("retry handler", handler) ;
        assertEquals("handler class", AbstractHttpMethodFactory.HttpMethodRetryHandlerWrapper.class, handler.getClass()) ;
    }
View Full Code Here


    private void testRetryHandler(final String method)
        throws Exception
    {
        final Class<?> handlerClass = RetryHandler.class ;
        final HttpMethodBase httpMethodBase = executeTest(method, handlerClass.getName()) ;
        final HttpMethodParams params = httpMethodBase.getParams() ;
        final Object handler = params.getParameter(HttpMethodParams.RETRY_HANDLER) ;
        assertNotNull("retry handler", handler) ;
        assertEquals("handler class", handlerClass, handler.getClass()) ;
    }
View Full Code Here

    private void testConfigurableRetryHandler(final String method)
        throws Exception
    {
        final Class<ConfigurableRetryHandler> handlerClass = ConfigurableRetryHandler.class ;
        final HttpMethodBase httpMethodBase = executeTest(method, handlerClass.getName()) ;
        final HttpMethodParams params = httpMethodBase.getParams() ;
        final Object handler = params.getParameter(HttpMethodParams.RETRY_HANDLER) ;
        assertNotNull("retry handler", handler) ;
        assertEquals("handler class", handlerClass, handler.getClass()) ;
        final ConfigurableRetryHandler configurableRetryHandler = handlerClass.cast(handler) ;
        assertNotNull("config", configurableRetryHandler.getConfig()) ;
View Full Code Here

        } else if(url.startsWith(JBossWSFactory.ESB_INTERNAL_URI)) {
            originalStream = JBossWSFactory.getFactory().getWsdl(url) ;
        } else if(url.startsWith("classpath://")) {
          originalStream = ClassUtil.getResource(url.substring(12, url.length()), getClass()).openStream();
        } else {
            HttpMethodBase httpMethod;
           
            try {
          HttpMethodFactory methodFactory = HttpMethodFactory.Factory.getInstance("GET", config, new URL(url));
          httpMethod = methodFactory.getInstance(null);
        } catch (ConfigurationException ce) {
          throw (IOException)(new IOException(ce.getMessage()).initCause(ce));
        }

            // Authentication is not being overridden on the method.  It needs
            // to be present on the supplied HttpClient instance!
            httpMethod.setDoAuthentication(true);

            try {
              int result = httpClient.executeMethod(httpMethod);

                if(result != HttpStatus.SC_OK) {
                    if(result < 200 || result > 299) {
                        throw new HttpException("Received status code '" + result + "' on WSDL HTTP (GET) request: '" + url + "'.");
                    } else {
                        logger.warn("Received status code '" + result + "' on WSDL HTTP (GET) request: '" + url + "'.");
                    }
                }
               
                originalBytes = httpMethod.getResponseBody();
                charsetNameDetected = httpMethod.getResponseCharSet();
            } finally {
                httpMethod.releaseConnection();
            }
        }
       
        String charsetName = (charsetNameOverride != null ? charsetNameOverride : charsetNameDetected);
        if (charsetName != null) {
View Full Code Here

        String urlStr = url.toString();

        log.debug("Start : sample " + urlStr);
        log.debug("method " + method);

        HttpMethodBase httpMethod = null;

        HTTPSampleResult res = new HTTPSampleResult();
        res.setMonitor(isMonitor());

        res.setSampleLabel(urlStr); // May be replaced later
        res.setHTTPMethod(method);
        res.setURL(url);

        res.sampleStart(); // Count the retries as well in the time
        try {
            // May generate IllegalArgumentException
            if (method.equals(HTTPConstants.POST)) {
                httpMethod = new PostMethod(urlStr);
            } else if (method.equals(HTTPConstants.PUT)){
                httpMethod = new PutMethod(urlStr);
            } else if (method.equals(HTTPConstants.HEAD)){
                httpMethod = new HeadMethod(urlStr);
            } else if (method.equals(HTTPConstants.TRACE)){
                httpMethod = new TraceMethod(urlStr);
            } else if (method.equals(HTTPConstants.OPTIONS)){
                httpMethod = new OptionsMethod(urlStr);
            } else if (method.equals(HTTPConstants.DELETE)){
                httpMethod = new EntityEnclosingMethod(urlStr) {
                    @Override
                    public String getName() { // HC3.1 does not have the method
                        return HTTPConstants.DELETE;
                    }
                };
            } else if (method.equals(HTTPConstants.GET)){
                httpMethod = new GetMethod(urlStr);
            } else if (method.equals(HTTPConstants.PATCH)){
                httpMethod = new EntityEnclosingMethod(urlStr) {
                    @Override
                    public String getName() { // HC3.1 does not have the method
                        return HTTPConstants.PATCH;
                    }
                };
            } else {
                throw new IllegalArgumentException("Unexpected method: '"+method+"'");
            }

            final CacheManager cacheManager = getCacheManager();
            if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method)) {
               if (cacheManager.inCache(url)) {
                   res.sampleEnd();
                   res.setResponseNoContent();
                   res.setSuccessful(true);
                   return res;
               }
            }

            // Set any default request headers
            setDefaultRequestHeaders(httpMethod);

            // Setup connection
            HttpClient client = setupConnection(url, httpMethod, res);
            savedClient = client;

            // Handle the various methods
            if (method.equals(HTTPConstants.POST)) {
                String postBody = sendPostData((PostMethod)httpMethod);
                res.setQueryString(postBody);
            } else if (method.equals(HTTPConstants.PUT) || method.equals(HTTPConstants.PATCH)
                    || method.equals(HTTPConstants.DELETE)) {
                String putBody = sendEntityData((EntityEnclosingMethod) httpMethod);
                res.setQueryString(putBody);
            }

            int statusCode = client.executeMethod(httpMethod);

            // We've finished with the request, so we can add the LocalAddress to it for display
            final InetAddress localAddr = client.getHostConfiguration().getLocalAddress();
            if (localAddr != null) {
                httpMethod.addRequestHeader(HEADER_LOCAL_ADDRESS, localAddr.toString());
            }
            // Needs to be done after execute to pick up all the headers
            res.setRequestHeaders(getConnectionHeaders(httpMethod));

            // Request sent. Now get the response:
            InputStream instream = httpMethod.getResponseBodyAsStream();

            if (instream != null) {// will be null for HEAD
                instream = new CountingInputStream(instream);
                try {
                    Header responseHeader = httpMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
                    if (responseHeader!= null && HTTPConstants.ENCODING_GZIP.equals(responseHeader.getValue())) {
                        InputStream tmpInput = new GZIPInputStream(instream); // tmp inputstream needs to have a good counting
                        res.setResponseData(readResponse(res, tmpInput, (int) httpMethod.getResponseContentLength()));                       
                    } else {
                        res.setResponseData(readResponse(res, instream, (int) httpMethod.getResponseContentLength()));
                    }
                } finally {
                    JOrphanUtils.closeQuietly(instream);
                }
            }

            res.sampleEnd();
            // Done with the sampling proper.

            // Now collect the results into the HTTPSampleResult:

            res.setSampleLabel(httpMethod.getURI().toString());
            // Pick up Actual path (after redirects)

            res.setResponseCode(Integer.toString(statusCode));
            res.setSuccessful(isSuccessCode(statusCode));

            res.setResponseMessage(httpMethod.getStatusText());

            String ct = null;
            Header h = httpMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE);
            if (h != null)// Can be missing, e.g. on redirect
            {
                ct = h.getValue();
                res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1
                res.setEncodingAndType(ct);
            }

            res.setResponseHeaders(getResponseHeaders(httpMethod));
            if (res.isRedirect()) {
                final Header headerLocation = httpMethod.getResponseHeader(HTTPConstants.HEADER_LOCATION);
                if (headerLocation == null) { // HTTP protocol violation, but avoids NPE
                    throw new IllegalArgumentException("Missing location header");
                }
                try {
                    String redirectLocation = headerLocation.getValue();
                    if(!STRICT_RFC_2616 && !(redirectLocation.startsWith("http://")||redirectLocation.startsWith("https://"))) {
                        redirectLocation = ConversionUtils.buildFullUrlFromRelative(url, redirectLocation);
                    }

                    res.setRedirectLocation(ConversionUtils.sanitizeUrl(new URL(redirectLocation)).toString());
                } catch (Exception e) {
                    log.error("Error sanitizing URL:"+headerLocation.getValue()+", message:"+e.getMessage());
                }
            }

            // record some sizes to allow HTTPSampleResult.getBytes() with different options
            if (instream != null) {
                res.setBodySize(((CountingInputStream) instream).getCount());
            }
            res.setHeadersSize(calculateHeadersSize(httpMethod));
            if (log.isDebugEnabled()) {
                log.debug("Response headersSize=" + res.getHeadersSize() + " bodySize=" + res.getBodySize()
                        + " Total=" + (res.getHeadersSize() + res.getBodySize()));
            }
           
            // If we redirected automatically, the URL may have changed
            if (getAutoRedirects()){
                res.setURL(new URL(httpMethod.getURI().toString()));
            }

            // Store any cookies received in the cookie manager:
            saveConnectionCookies(httpMethod, res.getURL(), getCookieManager());

            // Save cache information
            if (cacheManager != null){
                cacheManager.saveDetails(httpMethod, res);
            }

            // Follow redirects and download page resources if appropriate:
            res = resultProcessing(areFollowingRedirect, frameDepth, res);

            log.debug("End : sample");
            return res;
        } catch (IllegalArgumentException e) { // e.g. some kinds of invalid URL
            res.sampleEnd();
            // pick up headers if failed to execute the request
            // httpMethod can be null if method is unexpected
            if(httpMethod != null) {
                res.setRequestHeaders(getConnectionHeaders(httpMethod));
            }
            errorResult(e, res);
            return res;
        } catch (IOException e) {
            res.sampleEnd();
            // pick up headers if failed to execute the request
            res.setRequestHeaders(getConnectionHeaders(httpMethod));
            errorResult(e, res);
            return res;
        } finally {
            savedClient = null;
            if (httpMethod != null) {
                httpMethod.releaseConnection();
            }
        }
    }
View Full Code Here

     */
    protected InputStream getInputStreamForUrl(URL url) throws Exception {
        String fullLocation = url.toString();

        HttpClient client = new HttpClient();
        HttpMethodBase method = new GetMethod(fullLocation);
        prepareHttpClient(client, method);
        int status = client.executeMethod(method);

        switch (status) {
        case HttpStatus.SC_OK: {
            break; // good to go
        }

        case HttpStatus.SC_NOT_FOUND: {
            throw new Exception("Could not find the content at URL [" + fullLocation
                + "]. Make sure the content source defines a valid URL.");
        }

        case HttpStatus.SC_UNAUTHORIZED:
        case HttpStatus.SC_FORBIDDEN: {
            throw new Exception("Invalid login credentials specified for user [" + username + "]. Make sure "
                + "this user is valid and the password specified for this content source is correct.");
        }

        default: {
            throw new Exception("Failed to retrieve content. status code=" + status);
        }
        }

        InputStream stream = method.getResponseBodyAsStream();

        return stream;
    }
View Full Code Here

        serverMock.addTransaction(new WaitTransaction(2000));

        long start = System.currentTimeMillis();

        HttpClient client = createClient(10, 1);
        HttpMethodBase method = createGetMethod();
        try {
            HttpStatusCode statusCode = client.executeMethod(method);
            assertEquals(HttpStatusCode.OK, statusCode);
        } catch (InterruptedIOException expected) {
            long end = System.currentTimeMillis();
View Full Code Here

     * Create an initialised get method.
     *
     * @return The method.
     */
    private HttpMethodBase createGetMethod() {
        HttpMethodBase method = new GetMethod();
        initialiseMethod(method);
        return method;
    }
View Full Code Here

  protected static final String CONTENTS = "id\n100\n101\n102";

  @Test
  public void testCacheVetoHandler() throws Exception {
    File f=makeFile(CONTENTS);
    HttpMethodBase m=getUpdateMethod("GET");
    m.setQueryString(new NameValuePair[] { new NameValuePair("stream.file",f.getCanonicalPath())});
    getClient().executeMethod(m);
    assertEquals(200, m.getStatusCode());
    checkVetoHeaders(m, true);
  }
View Full Code Here

    checkVetoHeaders(m, true);
  }
 
  @Test
  public void testCacheVetoException() throws Exception {
    HttpMethodBase m = getSelectMethod("GET");
    // We force an exception from Solr. This should emit "no-cache" HTTP headers
    m.setQueryString(new NameValuePair[] { new NameValuePair("q", "xyz_ignore_exception:solr"),
        new NameValuePair("qt", "standard") });
    getClient().executeMethod(m);
    assertFalse(m.getStatusCode() == 200);
    checkVetoHeaders(m, false);
  }
View Full Code Here

TOP

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

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.