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:com.cerema.cloud2.lib.common.OwnCloudClient.java

public RedirectionPath followRedirection(HttpMethod method) throws IOException {
    int redirectionsCount = 0;
    int status = method.getStatusCode();
    RedirectionPath result = new RedirectionPath(status, MAX_REDIRECTIONS_COUNT);
    while (redirectionsCount < MAX_REDIRECTIONS_COUNT && (status == HttpStatus.SC_MOVED_PERMANENTLY
            || status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_TEMPORARY_REDIRECT)) {

        Header location = method.getResponseHeader("Location");
        if (location == null) {
            location = method.getResponseHeader("location");
        }//from www  .  ja  va  2s .c om
        if (location != null) {
            Log_OC.d(TAG + " #" + mInstanceNumber, "Location to redirect: " + location.getValue());

            String locationStr = location.getValue();
            result.addLocation(locationStr);

            // Release the connection to avoid reach the max number of connections per host
            // due to it will be set a different url
            exhaustResponse(method.getResponseBodyAsStream());
            method.releaseConnection();

            method.setURI(new URI(locationStr, true));
            Header destination = method.getRequestHeader("Destination");
            if (destination == null) {
                destination = method.getRequestHeader("destination");
            }
            if (destination != null) {
                int suffixIndex = locationStr.lastIndexOf(
                        (mCredentials instanceof OwnCloudBearerCredentials) ? AccountUtils.ODAV_PATH
                                : AccountUtils.WEBDAV_PATH_4_0);
                String redirectionBase = locationStr.substring(0, suffixIndex);

                String destinationStr = destination.getValue();
                String destinationPath = destinationStr.substring(mBaseUri.toString().length());
                String redirectedDestination = redirectionBase + destinationPath;

                destination.setValue(redirectedDestination);
                method.setRequestHeader(destination);
            }
            status = super.executeMethod(method);
            result.addStatus(status);
            redirectionsCount++;

        } else {
            Log_OC.d(TAG + " #" + mInstanceNumber, "No location to redirect!");
            status = HttpStatus.SC_NOT_FOUND;
        }
    }
    return result;
}

From source file:br.com.edu.dbpediaspotlight.AnnotationClient.java

public String request(HttpMethod method) throws AnnotationException {
    String response = null;//from   w w  w  .j  av  a  2  s .  c  o m
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody(); //TODO Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        response = new String(responseBody);

    } catch (HttpException e) {
        LOG.error("Fatal protocol violation: " + e.getMessage());
        throw new AnnotationException("Protocol error executing HTTP request.", e);
    } catch (IOException e) {
        LOG.error("Fatal transport error: " + e.getMessage());
        LOG.error(method.getQueryString());
        throw new AnnotationException("Transport error executing HTTP request.", e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return response;

}

From source file:ixa.pipe.ned.DBpediaSpotlightClient.java

public String request(HttpMethod method) throws AnnotationException {

    String response = null;//w  w  w .  j ava  2 s.  c om

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        // // Deal with the response.
        // // Use caution: ensure correct character encoding and is not binary data
        InputStream responseBody = method.getResponseBodyAsStream();
        response = StreamUtils.copyToString(responseBody, Charset.forName("UTF-8"));

    } catch (HttpException e) {
        LOG.error("Fatal protocol violation: " + e.getMessage());
        throw new AnnotationException("Protocol error executing HTTP request.", e);
    } catch (IOException e) {
        LOG.error("Fatal transport error: " + e.getMessage());
        LOG.error(method.getQueryString());
        throw new AnnotationException("Transport error executing HTTP request.", e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return response;

}

From source file:com.liferay.util.Http.java

public static byte[] URLtoByteArray(String location, Cookie[] cookies, boolean post) throws IOException {

    byte[] byteArray = null;

    HttpMethod method = null;

    try {// w w  w. j  av  a 2 s.c  om
        HttpClient client = new HttpClient(new SimpleHttpConnectionManager());

        if (location == null) {
            return byteArray;
        } else if (!location.startsWith(HTTP_WITH_SLASH) && !location.startsWith(HTTPS_WITH_SLASH)) {

            location = HTTP_WITH_SLASH + location;
        }

        HostConfiguration hostConfig = new HostConfiguration();

        hostConfig.setHost(new URI(location));

        if (Validator.isNotNull(PROXY_HOST) && PROXY_PORT > 0) {
            hostConfig.setProxy(PROXY_HOST, PROXY_PORT);
        }

        client.setHostConfiguration(hostConfig);
        client.setConnectionTimeout(5000);
        client.setTimeout(5000);

        if (cookies != null && cookies.length > 0) {
            HttpState state = new HttpState();

            state.addCookies(cookies);
            state.setCookiePolicy(CookiePolicy.COMPATIBILITY);

            client.setState(state);
        }

        if (post) {
            method = new PostMethod(location);
        } else {
            method = new GetMethod(location);
        }

        method.setFollowRedirects(true);

        client.executeMethod(method);

        Header locationHeader = method.getResponseHeader("location");
        if (locationHeader != null) {
            return URLtoByteArray(locationHeader.getValue(), cookies, post);
        }

        InputStream is = method.getResponseBodyAsStream();

        if (is != null) {
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            byte[] bytes = new byte[512];

            for (int i = is.read(bytes, 0, 512); i != -1; i = is.read(bytes, 0, 512)) {

                buffer.write(bytes, 0, i);
            }

            byteArray = buffer.toByteArray();

            is.close();
            buffer.close();
        }

        return byteArray;
    } finally {
        try {
            if (method != null) {
                method.releaseConnection();
            }
        } catch (Exception e) {
            Logger.error(Http.class, e.getMessage(), e);
        }
    }
}

From source file:ait.ffma.service.preservation.riskmanagement.api.PreservationRiskmanagementServiceImpl.java

/**
 * This method tries to establish HTTP connection for passed URI
 * @param uri The URI to verify// w  w w.  j a  v  a  2 s. co  m
 * @param responseLineList 
 *        This list collects response lines for broken URIs
 * @param brokenUriList
 *        This list collects broken URIs
 */
private void verifyUri(String uri, List<String> responseLineList, List<String> brokenUriList) {
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
    try {
        HttpMethod method = new GetMethod(uri);
        method.setFollowRedirects(true);
        client.executeMethod(method);
        int response = method.getStatusCode();
        if (response != 200) {
            StatusLine responseLine = method.getStatusLine();
            log.info("uri: " + uri + ", response: " + response + ", responseLine: " + responseLine.toString());
            brokenUriList.add(uri);
            responseLineList.add(responseLine.toString());
        }
        method.releaseConnection();
    } catch (IOException e) {
        log.info("Unable to connect to " + uri + " verification error: " + e);
        brokenUriList.add(uri);
        responseLineList.add(e.getMessage());
    }
}

From source file:com.npower.dm.msm.tools.PackageCheckerImpl.java

public PackageMetaInfo getPackageMetaInfo(String url) throws DMException {
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    PackageMetaInfo metaInfo = new PackageMetaInfo();
    metaInfo.setUrl(url);//  ww w  . ja  v a2  s. com
    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);
        metaInfo.setServerStatus(statusCode);
        if (statusCode != HttpStatus.SC_OK) {
            // System.err.println("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();
        System.out.println(new String(responseBody));

        Header mimeType = method.getResponseHeader("Content-Type");
        if (mimeType != null) {
            metaInfo.setMimeType(mimeType.getValue());
        }

        Header contentLength = method.getResponseHeader("Content-Length");
        if (contentLength != null && StringUtils.isNotEmpty(contentLength.getValue())) {
            metaInfo.setSize(Integer.parseInt(contentLength.getValue()));
        }

    } catch (HttpException e) {
        metaInfo.setErrorMessage(e.getMessage());
    } catch (IOException e) {
        metaInfo.setErrorMessage(e.getMessage());
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return metaInfo;
}

From source file:AnnotationClient.java

public String request(HttpMethod method) throws AnnotationException {

    String response = null;// w w  w  .j  a v  a2  s  . c o  m

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody(); //TODO Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        response = new String(responseBody);

    } catch (HttpException e) {
        LOG.error("Fatal protocol violation: " + e.getMessage());
        throw new AnnotationException("Protocol error executing HTTP request.", e);
    } catch (IOException e) {
        LOG.error("Fatal transport error: " + e.getMessage());
        LOG.error(method.getQueryString());
        throw new AnnotationException("Transport error executing HTTP request.", e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return response;

}

From source file:arena.httpclient.commons.JakartaCommonsHttpClient.java

public HttpResponse get() throws IOException {
    NameValuePair params[] = new NameValuePair[0];
    if (this.requestParameters != null) {
        List<NameValuePair> paramList = new ArrayList<NameValuePair>();
        for (String key : this.requestParameters.keySet()) {
            String[] multipleValues = this.requestParameters.get(key);
            for (String value : multipleValues) {
                paramList.add(new NameValuePair(key, value));
            }//from   w ww  . j  av a 2s.  c  o  m
        }
        params = paramList.toArray(new NameValuePair[paramList.size()]);
    }

    HttpMethod method = null;
    if (this.isPost) {
        method = new PostMethod(this.url);
        if (this.encoding != null) {
            method.getParams().setContentCharset(this.encoding);
        }
        ((PostMethod) method).setRequestBody(params);
    } else {
        String url = this.url;
        for (int n = 0; n < params.length; n++) {
            url = URLUtils.addParamToURL(url, params[n].getName(), params[n].getValue(), this.encoding, false);
        }
        method = new GetMethod(url);
        method.setFollowRedirects(true);
        if (this.encoding != null) {
            method.getParams().setContentCharset(this.encoding);
        }
    }

    HttpClient client = new HttpClient(this.manager);
    if (this.connectTimeout != null) {
        client.getHttpConnectionManager().getParams().setConnectionTimeout(this.connectTimeout.intValue());
    }
    if (this.readTimeout != null) {
        client.getHttpConnectionManager().getParams().setSoTimeout(this.readTimeout.intValue());
    }
    client.setState(this.state);
    try {
        int statusCode = client.executeMethod(method);
        return new HttpResponse(getResponseBytes(method), statusCode,
                buildHeaderMap(method.getResponseHeaders()));
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:com.yahoo.flowetl.services.HttpService.java

/**
 * Calls the given http params and returns a result object.
 * //from   w  w w . java2 s  . com
 * @param params
 * 
 * @return the http result
 */
public HttpResult call(HttpParams params) {
    Pair<HttpClient, HttpMethod> clientMet = generator.generate(params);
    HttpClient client = clientMet.getFirst();
    HttpMethod toCall = clientMet.getSecond();
    HttpResult out = new HttpResult();
    out.statusCode = -1;
    out.sourceParams = params;
    InputStream is = null;
    try {
        if (logger.isEnabled(Level.INFO)) {
            logger.log(Level.INFO, "Running http method " + toCall + " with params " + params);
        }
        caller.execute(client, toCall, params.retries);
        is = toCall.getResponseBodyAsStream();
        String responseBody = IOUtils.toString(is);
        int st = toCall.getStatusCode();
        Header[] hv = toCall.getResponseHeaders();
        // copy over
        out.statusCode = st;
        out.responseBody = responseBody;
        Map<String, String> headersIn = new TreeMap<String, String>();
        if (hv != null) {
            for (Header h : hv) {
                headersIn.put(h.getName(), h.getValue());
            }
        }
        out.headers = headersIn;
    } catch (HttpException e) {
        if (logger.isEnabled(Level.WARN)) {
            logger.log(Level.WARN, e, "Failed calling " + toCall);
        }
    } catch (IOException e) {
        if (logger.isEnabled(Level.WARN)) {
            logger.log(Level.WARN, e, "Failed calling " + toCall);
        }
    } finally {
        IOUtils.closeQuietly(is);
        toCall.releaseConnection();
    }
    return out;
}

From source file:it.drwolf.ridire.session.CrawlerManager.java

@Restrict("#{s:hasRole('Crawler User')}")
public void stopJob(String jobName, User currentUser) throws HeritrixException {
    this.updateJobsList(currentUser);
    HttpMethod method = null;
    try {//from  w  w w . jav  a 2 s .  co  m
        method = new PostMethod(this.engineUri + "job/" + URLEncoder.encode(jobName, "UTF-8"));
        ((PostMethod) method).addParameter(new NameValuePair("action", "terminate"));
        // TODO check status
        int status = this.httpClient.executeMethod(method);
        method.releaseConnection();
        this.updateJobsList(currentUser);
    } catch (IOException e) {
        e.printStackTrace();
        throw new HeritrixException();
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}