Example usage for org.apache.commons.httpclient HttpMethod releaseConnection

List of usage examples for org.apache.commons.httpclient HttpMethod releaseConnection

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod releaseConnection.

Prototype

public abstract void releaseConnection();

Source Link

Usage

From source file:org.apache.wookie.proxy.ProxyClient.java

private String executeMethod(HttpMethod method, Configuration properties)
        throws Exception, AuthenticationException {
    // Execute the method.
    try {//from   w w  w .  j a va 2s. co  m
        HttpClient client = new HttpClient();

        // set the clients proxy values if needed
        ConnectionsPrefsManager.setProxySettings(client, properties);

        if (fUseProxyAuthentication) {
            if (fBase64Auth != null) {
                method.setRequestHeader("Authorization", fBase64Auth);
            } else {
                List<String> authPrefs = new ArrayList<String>(2);
                authPrefs.add(AuthPolicy.DIGEST);
                authPrefs.add(AuthPolicy.BASIC);
                client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
                // send the basic authentication response even before the server gives an unauthorized response
                client.getParams().setAuthenticationPreemptive(true);
                // Pass our credentials to HttpClient
                client.getState().setCredentials(
                        new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
                        new UsernamePasswordCredentials(fProxyUsername, fProxyPassword));
            }
        }

        // Add user language to http request in order to notify server of user's language
        Locale locale = Locale.getDefault();

        method.setRequestHeader("Accept-Language", locale.getLanguage()); //$NON-NLS-1$
        method.removeRequestHeader("Content-Type");
        //method.setRequestHeader("Content-Type","application/json");
        //method.setRequestHeader("Referer", "");
        //method.removeRequestHeader("Referer");
        method.setRequestHeader("Accept", "*/*");

        int statusCode = client.executeMethod(method);

        //System.out.println("response="+method.getResponseBodyAsString());
        //System.out.println("method="+method.toString());
        //System.out.println("response="+method.getResponseBodyAsStream());

        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
            Header hType = method.getResponseHeader("Content-Type");
            if (hType != null) {
                fContentType = hType.getValue();
            }
            // for now we are only expecting Strings
            //return method.getResponseBodyAsString();
            return readFully(new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8"));
        } else if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED
                || statusCode == HttpStatus.SC_UNAUTHORIZED) {
            throw new AuthenticationException("Authentication failed:" + method.getStatusLine() + ' '
                    + method.getURI() + ' ' + method.getStatusText());
        } else {
            throw new Exception("Method failed: " + method.getStatusLine() + ' ' + method.getURI() + ' ' //$NON-NLS-1$
                    + method.getStatusText());
        }
    } catch (IOException e) {
        throw e;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:org.apache.wookie.tests.functional.ProxyTest.java

@Test
public void getValidSiteAndValidXMLContentType() throws Exception {
    String url = PROXY_URL + "?instanceid_key=" + instance_id_key + "&url=" + VALID_SITE_XML_URL;
    HttpClient client = new HttpClient();
    HttpMethod req = new GetMethod(url);
    client.executeMethod(req);/*ww  w. j ava 2s.  co m*/
    int code = req.getStatusCode();
    req.releaseConnection();
    assertEquals(200, code);
    assertTrue(req.getResponseHeader("Content-Type").toString().contains("text/xml"));
}

From source file:org.apache.wookie.tests.functional.ProxyTest.java

@Test
public void getValidSiteAndValidHTMLContentType() throws Exception {
    String url = PROXY_URL + "?instanceid_key=" + instance_id_key + "&url=" + VALID_SITE_URL;
    HttpClient client = new HttpClient();
    HttpMethod req = new GetMethod(url);
    client.executeMethod(req);//from  w w  w  .  ja  va  2 s .  c om
    int code = req.getStatusCode();
    req.releaseConnection();
    assertEquals(200, code);
    assertTrue(req.getResponseHeader("Content-Type").toString().contains("text/html"));
}

From source file:org.apache.wookie.tests.functional.ProxyTest.java

@Test
public void getProtectedSiteWithoutAuth() throws Exception {
    HttpClient client = new HttpClient();
    HttpMethod req;
    req = new GetMethod(PROXY_URL + "?instanceid_key=" + instance_id_key + "&url=" + PROTECTED_SITE_URL);
    client.executeMethod(req);//from   w ww  . j  a va2 s.c  o m
    int code = req.getStatusCode();
    req.releaseConnection();
    assertEquals(401, code);
}

From source file:org.apache.wookie.tests.functional.ProxyTest.java

@Test
public void getProtectedSiteWithBasicAuth() throws Exception {
    HttpClient client = new HttpClient();
    List<String> authPrefs = new ArrayList<String>(2);
    authPrefs.add(AuthPolicy.DIGEST);/*from   w ww  .  java2s. co m*/
    authPrefs.add(AuthPolicy.BASIC);
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    // send the basic authentication response even before the server gives an unauthorized response
    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
            new UsernamePasswordCredentials("java", "java"));
    HttpMethod req;
    req = new GetMethod(PROXY_URL + "?instanceid_key=" + instance_id_key + "&url=" + PROTECTED_SITE_URL);
    client.executeMethod(req);
    int code = req.getStatusCode();
    req.releaseConnection();
    assertEquals(200, code);
}

From source file:org.apache.wookie.tests.functional.ProxyTest.java

private int send(String url, String method) {
    try {/*from  w  w  w  .  j ava  2s  .  c o  m*/
        HttpClient client = new HttpClient();
        HttpMethod req;
        if (method.equals("POST")) {
            req = new PostMethod(url);
        } else {
            req = new GetMethod(url);
        }
        client.executeMethod(req);
        int code = req.getStatusCode();
        req.releaseConnection();
        return code;
    } catch (Exception e) {
        e.printStackTrace();
        fail("post failed");
        return -1;
    }
}

From source file:org.apache.wookie.util.gadgets.GadgetUtils.java

/**
 * Call a remote service// w ww .j av a  2  s .  co m
 * @param method the method to invoke
 * @return the response from the remote service
 * @throws Exception
 */
private static String executeMethod(HttpMethod method) throws Exception {
    // Execute the method.
    System.out.println("executeMethod() start");
    try {
        HttpClient client = new HttpClient();

        // Add user language to http request in order to notify server of user's language
        Locale locale = Locale.getDefault();

        method.setRequestHeader("Accept-Language", locale.getLanguage()); //$NON-NLS-1$ 
        int statusCode = client.executeMethod(method);
        System.out.println("HTTP client returned status:" + statusCode);
        if (statusCode == HttpStatus.SC_OK) {
            // for now we are only expecting Strings               
            return method.getResponseBodyAsString();
        } else {
            throw new Exception("Method failed: " + method.getStatusLine() + ' ' + method.getURI() + ' ' //$NON-NLS-1$
                    + method.getStatusText() + method.getResponseBodyAsString());
        }
    } catch (IOException e) {
        System.out.println("CaughtIOException");
        throw new Exception("ERROR_CONNECT", e);
    } finally {
        // Release the connection.
        System.out.println("executeMethod() end");
        method.releaseConnection();
    }
}

From source file:org.archive.crawler.fetcher.FetchHTTP.java

/**
 * Cleanup after a failed method execute.
 * @param curi CrawlURI we failed on.//from   w  ww  .  ja  v  a 2 s .c o m
 * @param method Method we failed on.
 * @param exception Exception we failed with.
 */
private void failedExecuteCleanup(final HttpMethod method, final CrawlURI curi, final Exception exception) {
    cleanup(curi, exception, "executeMethod", (method.isRequestSent() ? S_CONNECT_LOST : S_CONNECT_FAILED));
    method.releaseConnection();
}

From source file:org.archive.wayback.liveweb.ArcRemoteLiveWebCache.java

public Resource getCachedResource(URL url, long maxCacheMS, boolean bUseOlder)
        throws LiveDocumentNotAvailableException, LiveWebCacheUnavailableException, LiveWebTimeoutException,
        IOException {/* ww w.j a v  a 2s .c  o  m*/
    String urlString = url.toExternalForm();

    if (requestPrefix != null) {
        urlString = requestPrefix + urlString;
    }

    HttpMethod method = null;
    try {
        method = new GetMethod(urlString);
    } catch (IllegalArgumentException e) {
        LOGGER.warning("Bad URL for live web fetch:" + urlString);
        throw new LiveDocumentNotAvailableException("Url:" + urlString + "does not look like an URL?");
    }
    boolean success = false;
    try {
        int status = http.executeMethod(method);
        if (status == 200) {

            ByteArrayInputStream bais = new ByteArrayInputStream(method.getResponseBody());
            ARCRecord r = new ARCRecord(new GZIPInputStream(bais), "id", 0L, false, false, true);
            ArcResource ar = (ArcResource) ResourceFactory.ARCArchiveRecordToResource(r, null);
            if (ar.getStatusCode() == 502) {
                throw new LiveDocumentNotAvailableException(urlString);
            } else if (ar.getStatusCode() == 504) {
                throw new LiveWebTimeoutException("Timeout:" + urlString);
            }
            success = true;
            return ar;

        } else {
            throw new LiveWebCacheUnavailableException(urlString);
        }

    } catch (ResourceNotAvailableException e) {
        throw new LiveDocumentNotAvailableException(urlString);

    } catch (NoHttpResponseException e) {

        throw new LiveWebCacheUnavailableException("No Http Response for " + urlString);

    } catch (ConnectException e) {
        throw new LiveWebCacheUnavailableException(e.getLocalizedMessage() + " : " + urlString);
    } catch (SocketException e) {
        throw new LiveWebCacheUnavailableException(e.getLocalizedMessage() + " : " + urlString);
    } catch (SocketTimeoutException e) {
        throw new LiveWebTimeoutException(e.getLocalizedMessage() + " : " + urlString);
    } catch (ConnectTimeoutException e) {
        throw new LiveWebTimeoutException(e.getLocalizedMessage() + " : " + urlString);
    } finally {
        if (!success) {
            method.abort();
        }
        method.releaseConnection();
    }
}

From source file:org.archive.wayback.liveweb.ARCUnwrappingProxy.java

public boolean handleRequest(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
        throws ServletException, IOException {
    StringBuffer sb = httpRequest.getRequestURL();
    String query = httpRequest.getQueryString();
    if (query != null) {
        sb.append("?").append(query);
    }/*from  w w  w .  j  a  v a 2  s  .  c  om*/
    HttpMethod method = new GetMethod(sb.toString());
    boolean got200 = false;
    try {
        HttpClient http = new HttpClient(connectionManager);
        http.setHostConfiguration(hostConfiguration);

        int status = http.executeMethod(method);
        if (status == 200) {
            ARCRecord r = new ARCRecord(new GZIPInputStream(method.getResponseBodyAsStream()), "id", 0L, false,
                    false, true);
            Resource res = null;
            try {
                res = ResourceFactory.ARCArchiveRecordToResource(r, null);
            } catch (ResourceNotAvailableException e) {
                LOGGER.severe(e.getMessage());
                throw new IOException(e);
            }
            httpResponse.setStatus(res.getStatusCode());

            Map<String, String> headers = res.getHttpHeaders();
            Iterator<String> keys = headers.keySet().iterator();
            while (keys.hasNext()) {
                String key = keys.next();
                if (!key.equalsIgnoreCase("Connection") && !key.equalsIgnoreCase("Content-Length")
                        && !key.equalsIgnoreCase("Transfer-Encoding")) {
                    String value = headers.get(key);
                    httpResponse.addHeader(key, value);
                }
            }

            ByteOp.copyStream(res, httpResponse.getOutputStream());
            got200 = true;
        }
    } finally {
        method.releaseConnection();

    }

    return got200;
}