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.wafersystems.util.HttpUtil.java

/**
 * URL?//from w  w  w  .  java2  s.com
 * 
 * @param hClient   HttpClient
 * @param url      URL
 * 
 * @return
 * @throws Exception
 */
public static String openURL(HttpClient hClient, String url) throws Exception {
    HttpMethod method = null;
    try {
        //Get
        method = new GetMethod(url);
        // URL
        int result = hClient.executeMethod(method);
        //cookie?
        //getCookie(method.getURI().getHost(), method.getURI().getPort(), "/" , false , hClient.getState().getCookies());

        //???
        result = checkRedirect(method.getURI().getHost(), method.getURI().getPort(), hClient, method, result);

        if (result != HttpStatus.SC_OK)
            logger.error(method.getPath() + "" + method.getStatusLine().toString() + "\r\n"
                    + method.getResponseBodyAsString());

        return method.getResponseBodyAsString();
    } finally {
        method.releaseConnection();
    }
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Execute method with httpClient./*from w w  w . j  a v a  2 s.c  o m*/
 *
 * @param httpClient Http client instance
 * @param method     Http method
 * @return Http status
 * @throws IOException on error
 */
public static int executeHttpMethod(HttpClient httpClient, HttpMethod method) throws IOException {
    int status = 0;
    try {
        status = httpClient.executeMethod(method);
    } finally {
        method.releaseConnection();
    }
    return status;
}

From source file:com.intellij.diagnostic.DevelopersLoader.java

public static Collection<Developer> fetchDevelopers(ProgressIndicator indicator) throws IOException {
    List<Developer> developers = new LinkedList<Developer>();
    developers.add(Developer.NULL);//w  w  w . j a va  2s.com

    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(TIMEOUT);
    HttpMethod method = new GetMethod(DEVELOPERS_LIST_URL);

    try {
        client.executeMethod(method);

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(method.getResponseBodyAsStream(), DATA_CHARSET));

        try {
            while (true) {
                String line = reader.readLine();
                if (line == null)
                    break;
                int i = line.indexOf('\t');
                if (i == -1)
                    throw new IOException("Protocol error");
                int id = Integer.parseInt(line.substring(0, i));
                String name = line.substring(i + 1);
                developers.add(new Developer(id, name));
                indicator.checkCanceled();
            }
            return developers;
        } finally {
            reader.close();
        }
    } finally {
        method.releaseConnection();
    }
}

From source file:edu.du.penrose.systems.util.HttpClientUtils.java

/**
 * Appends response form URL to a StringBuffer
 * //from   w w w.  j a  va2 s  . c o m
 * @param requestUrl
 * @param resultStringBuffer
 * @return int request status code OR -1 if an exception occurred
 */
static public int getAsString(String requestUrl, StringBuffer resultStringBuffer) {
    HttpClient client = new HttpClient();

    //   client.getState().setCredentials(
    //         new AuthScope("localhost", 7080, null ),
    //         new UsernamePasswordCredentials("nation", "nationPW") 
    //     );
    //   client.getParams().setAuthenticationPreemptive(true);

    HttpMethod method = new GetMethod(requestUrl);

    // method.setDoAuthentication( true );   
    // client.getParams().setAuthenticationPreemptive(true);

    // Execute and print response
    try {
        client.executeMethod(method);
        InputStream is = method.getResponseBodyAsStream();
        BufferedInputStream bis = new BufferedInputStream(is);

        String datastr = null;
        byte[] bytes = new byte[8192]; // reading as chunk of 8192 bytes
        int count = bis.read(bytes);
        while (count != -1 && count <= 8192) {
            datastr = new String(bytes, 0, count);
            resultStringBuffer.append(datastr);
            count = bis.read(bytes);
        }
        bis.close();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        method.releaseConnection();
    }

    return method.getStatusCode();
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Get Http Status code for the given URL
 *
 * @param httpClient httpClient instance
 * @param url        url string//from   w w w. j  a v  a 2 s . c  o  m
 * @return HttpStatus code
 */
public static int getHttpStatus(HttpClient httpClient, String url) {
    int status = 0;
    HttpMethod testMethod = new GetMethod(url);
    testMethod.setDoAuthentication(false);
    try {
        status = httpClient.executeMethod(testMethod);
    } catch (IOException e) {
        LOGGER.warn(e.getMessage(), e);
    } finally {
        testMethod.releaseConnection();
    }
    return status;
}

From source file:fi.csc.mobileauth.shibboleth.rest.MobileServiceLoginHandler.java

private static StatusResponse getStatusResponse(String uri) {
    HttpMethod httpMethod = executeUriCall(uri);
    if (httpMethod == null) {
        log.debug("Could not execute call to URL {}", uri);
        return null;
    }/*from  w  w w.j  a va2 s .co  m*/
    try {
        InputStream content = httpMethod.getResponseBodyAsStream();
        ObjectMapper objectMapper = new ObjectMapper();
        StatusResponse response = objectMapper.readValue(content, StatusResponse.class);
        content.close();
        log.debug("Status response eventId={}, errorMessage={}", response.getEventId(),
                response.getErrorMessage());
        return response;
    } catch (IOException e) {
        log.error("Could not obtain response from the REST service!", e);
        return null;
    } finally {
        httpMethod.releaseConnection();
    }
}

From source file:edu.du.penrose.systems.util.HttpClientUtils.java

/**
 * Get file from URL, directories are created and files overwritten.
 * //w  w  w.  j  a  v a  2 s. c om
 * 
 * @deprecated use  org.apache.commons.io.FileUtils.copyURLToFile(URL, File)
 * @param requestUrl
 * @param outputPathAndFileName
 *
 * @return int request status code OR -1 if an exception occurred
 */
static public int getToFile(String requestUrl, String outputPathAndFileName) {
    int resultStatus = -1;

    File outputFile = new File(outputPathAndFileName);
    String outputPath = outputFile.getAbsolutePath().replace(outputFile.getName(), "");
    File outputDir = new File(outputPath);
    if (!outputDir.exists()) {
        outputDir.mkdir();
    }

    HttpClient client = new HttpClient();

    //   client.getState().setCredentials(
    //         new AuthScope("localhost", 7080, null ),
    //         new UsernamePasswordCredentials("nation", "nationPW") 
    //     );
    //   client.getParams().setAuthenticationPreemptive(true);

    HttpMethod method = new GetMethod(requestUrl);

    //   method.setDoAuthentication( true );   
    //  client.getParams().setAuthenticationPreemptive(true);

    // Execute and print response
    try {

        OutputStream os = new FileOutputStream(outputFile);

        client.executeMethod(method);
        InputStream is = method.getResponseBodyAsStream();
        BufferedInputStream bis = new BufferedInputStream(is);

        byte[] bytes = new byte[8192]; // reading as chunk of 8192 bytes
        int count = bis.read(bytes);
        while (count != -1 && count <= 8192) {
            os.write(bytes, 0, count);
            count = bis.read(bytes);
        }
        bis.close();
        os.close();
        resultStatus = method.getStatusCode();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        method.releaseConnection();
    }

    return resultStatus;
}

From source file:jshm.sh.client.HttpForm.java

/**
 * Will be called once the form is submitted. Can be overridden to perform
 * some action. If overridden, method.releaseConnection() should be called.
 * @param responseCode/*from   ww  w .ja va 2  s .c o  m*/
 * @param client
 * @param method
 */
public void afterSubmit(final int response, final HttpClient client, final HttpMethod method) throws Exception {
    method.releaseConnection();
}

From source file:com.zimbra.cs.util.WebClientServiceUtil.java

public static String sendServiceRequestToUiNode(Server server, String serviceUrl) throws ServiceException {
    if (isServerAtLeast8dot5(server)) {
        HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
        HttpProxyUtil.configureProxy(client);
        AuthToken authToken = AuthProvider.getAdminAuthToken();
        ZimbraLog.misc.debug("got admin auth token");
        String resp = "";
        HttpMethod method = null;
        try {//from  w  w  w .ja v a  2 s.  c  o  m
            method = new GetMethod(URLUtil.getServiceURL(server, serviceUrl, false));
            ZimbraLog.misc.debug("connecting to ui node %s", server.getName());
            method.addRequestHeader(PARAM_AUTHTOKEN, authToken.getEncoded());
            int result = HttpClientUtil.executeMethod(client, method);
            ZimbraLog.misc.debug("resp: %d", result);
            resp = method.getResponseBodyAsString();
            ZimbraLog.misc.debug("got response from ui node: %s", resp);
        } catch (IOException e) {
            ZimbraLog.misc.warn("failed to get response from ui node", e);
        } catch (AuthTokenException e) {
            ZimbraLog.misc.warn("failed to get authToken", e);
        } finally {
            if (method != null) {
                method.releaseConnection();
            }
        }
        if (authToken != null && authToken.isRegistered()) {
            try {
                authToken.deRegister();
                ZimbraLog.misc.debug("de-registered auth token, isRegistered?%s", authToken.isRegistered());
            } catch (AuthTokenException e) {
                ZimbraLog.misc.warn("failed to de-register authToken", e);
            }
        }
        return resp;
    }
    return "";
}

From source file:edu.uci.ics.external.connector.asterixdb.ConnectorUtils.java

private static int executeHttpMethod(HttpMethod method) throws Exception {
    HttpClient client = new HttpClient();
    int statusCode;
    try {/*from   ww w .  j av a 2s.  c  o  m*/
        statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            JSONObject result = new JSONObject(
                    new JSONTokener(new InputStreamReader(method.getResponseBodyAsStream())));
            if (result.has("error-code")) {
                String[] errors = { result.getJSONArray("error-code").getString(0), result.getString("summary"),
                        result.getString("stacktrace") };
                throw new Exception("HTTP operation failed: " + errors[0] + "\nSTATUS LINE: "
                        + method.getStatusLine() + "\nSUMMARY: " + errors[1] + "\nSTACKTRACE: " + errors[2]);
            }
        }
        return statusCode;
    } catch (Exception e) {
        throw e;
    } finally {
        method.releaseConnection();
    }
}