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.smartitengineering.util.rest.client.jersey.cache.CustomApacheHttpClientResponseResolver.java

private InputStream getInputStream(HttpMethod method) {
    try {/*  w  ww  . j a v a 2  s  . c o  m*/
        return method.getResponseBodyAsStream() != null ? new HttpMethodStream(method) : null;
    } catch (IOException e) {
        method.releaseConnection();
        throw new HTTPException("Unable to get InputStream from HttpClient", e);
    }
}

From source file:com.sina.stock.SinaStockClient.java

private Bitmap getBitmapFromUrl(String url) throws HttpException, IOException {

    HttpMethod method = new GetMethod(url);
    int statusCode = mHttpClient.executeMethod(method);
    if (statusCode != HttpStatus.SC_OK) {
        method.releaseConnection();
        return null;
    }/*from  ww  w. j ava 2 s .  c o  m*/

    InputStream in = method.getResponseBodyAsStream();
    BufferedInputStream bis = new BufferedInputStream(in);

    Bitmap bm = BitmapFactory.decodeStream(bis);

    bis.close();
    method.releaseConnection();

    return bm;
}

From source file:com.sina.stock.SinaStockClient.java

/**
 * ???//from  w  ww .j a  va2s.c o  m
 * 
 * @param stockCodes 
 *       ??"sh+?", ?"sz+?"
 * 
 * @return ?List<SinaStockInfo>null 
 *       
 * @throws IOException 
 * @throws HttpException 
 * @throws ParseStockInfoException 
 */
public List<SinaStockInfo> getStockInfo(String[] stockCodes)
        throws HttpException, IOException, ParseStockInfoException {
    String url = STOCK_URL + generateStockCodeRequest(stockCodes);

    HttpMethod method = new GetMethod(url);
    int statusCode = mHttpClient.executeMethod(method);
    if (statusCode != HttpStatus.SC_OK) {
        method.releaseConnection();
        return null;
    }

    InputStream is = method.getResponseBodyAsStream();
    InputStreamReader reader = new InputStreamReader(new BufferedInputStream(is), Charset.forName("gbk"));
    BufferedReader bReader = new BufferedReader(reader);

    List<SinaStockInfo> list = parseSinaStockInfosFromReader(bReader);
    bReader.close();
    method.releaseConnection();

    return list;
}

From source file:net.adamcin.httpsig.http.apache3.Http3UtilTest.java

@Test
public void testLogin() {
    TestBody.test(new HttpServerTestBody() {

        @Override/*from  w ww .j av a 2  s .com*/
        protected void execute() throws Exception {
            List<String> headers = Arrays.asList(Constants.HEADER_REQUEST_TARGET, Constants.HEADER_DATE);
            setServlet(new AdminServlet(headers));

            KeyPair keyPair = KeyTestUtil.getKeyPairFromProperties("b2048", "id_rsa");

            DefaultKeychain provider = new DefaultKeychain();
            provider.add(new SSHKey(KeyFormat.SSH_RSA, keyPair));

            HttpClient client = new HttpClient();

            Http3Util.enableAuth(client, provider, getKeyId());
            HttpMethod request = new GetMethod(getAbsoluteUrl(TEST_URL));
            try {
                int status = client.executeMethod(request);
                assertEquals("should return 200", 200, status);
            } finally {
                request.releaseConnection();
            }
        }
    });
}

From source file:apm.common.utils.HttpTookit.java

/**
 * HTTP GET?HTML// w  w  w  .  j  a v  a 2s. c  om
 * 
 * @param url
 *            URL?
 * @param queryString
 *            ?,?null
 * @param charset
 *            
 * @param pretty
 *            ?
 * @return ?HTML
 */
public static String doGet(String url, String queryString, String charset, boolean pretty) {
    StringBuffer response = new StringBuffer();
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    try {
        if (StringUtils.isNotBlank(queryString))
            // get??http?????%?
            method.setQueryString(URIUtil.encodeQuery(queryString));
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(method.getResponseBodyAsStream(), charset));
            String line;
            while ((line = reader.readLine()) != null) {
                if (pretty) {
                    response.append(line).append(System.getProperty("line.separator"));
                } else {
                    response.append(line);
                }
            }
            reader.close();
        }
    } catch (URIException e) {
        log.error("HTTP Get?" + queryString + "???", e);
    } catch (IOException e) {
        log.error("HTTP Get" + url + "??", e);
    } finally {
        method.releaseConnection();
    }
    return response.toString();
}

From source file:au.org.ala.spatial.util.UploadSpatialResource.java

/**
 * sends a PUT or POST call to a URL using authentication and including a
 * file upload/* w  ww .  j  a  v  a2  s . co m*/
 *
 * @param type         one of UploadSpatialResource.PUT for a PUT call or
 *                     UploadSpatialResource.POST for a POST call
 * @param url          URL for PUT/POST call
 * @param username     account username for authentication
 * @param password     account password for authentication
 * @param resourcepath local path to file to upload, null for no file to
 *                     upload
 * @param contenttype  file MIME content type
 * @return server response status code as String or empty String if
 * unsuccessful
 */
public static String httpCall(int type, String url, String username, String password, String resourcepath,
        String contenttype) {
    String output = "";

    HttpClient client = new HttpClient();
    client.setConnectionTimeout(10000);
    client.setTimeout(60000);
    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    RequestEntity entity = null;
    if (resourcepath != null) {
        File input = new File(resourcepath);
        entity = new FileRequestEntity(input, contenttype);
    }

    HttpMethod call = null;
    ;
    if (type == PUT) {
        PutMethod put = new PutMethod(url);
        put.setDoAuthentication(true);
        if (entity != null) {
            put.setRequestEntity(entity);
        }
        call = put;
    } else if (type == POST) {
        PostMethod post = new PostMethod(url);
        if (entity != null) {
            post.setRequestEntity(entity);
        }
        call = post;
    } else {
        //SpatialLogger.log("UploadSpatialResource", "invalid type: " + type);
        return output;
    }

    // Execute the request 
    try {
        int result = client.executeMethod(call);

        output = result + ": " + call.getResponseBodyAsString();
    } catch (Exception e) {
        //SpatialLogger.log("UploadSpatialResource", "failed upload to: " + url);
        output = "0: " + e.getMessage();
        e.printStackTrace(System.out);
    } finally {
        // Release current connection to the connection pool once you are done 
        call.releaseConnection();
    }

    return output;
}

From source file:fr.matriciel.AnnotationClient.java

public static String request(HttpMethod method) throws AnnotationException {

    String response = null;/* w  ww  .  jav  a  2s.  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) {
            System.out.println("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) {
        throw new AnnotationException("Protocol error executing HTTP request.", e);
    } catch (IOException e) {
        throw new AnnotationException("Transport error executing HTTP request.", e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return response;

}

From source file:net.adamcin.httpsig.http.apache3.Http3UtilTest.java

@Test
public void testAllHeaders() {
    TestBody.test(new HttpServerTestBody() {
        @Override/*from   w w w .jav a 2  s .  co  m*/
        protected void execute() throws Exception {
            List<String> headers = Arrays.asList(Constants.HEADER_REQUEST_TARGET, Constants.HEADER_DATE,
                    "x-test");

            setServlet(new AdminServlet(headers));

            KeyPair keyPair = KeyTestUtil.getKeyPairFromProperties("b2048", "id_rsa");

            DefaultKeychain provider = new DefaultKeychain();
            provider.add(new SSHKey(KeyFormat.SSH_RSA, keyPair));

            HttpClient client = new HttpClient();

            Http3Util.enableAuth(client, provider, getKeyId());
            HttpMethod request = new GetMethod(getAbsoluteUrl(TEST_URL));
            request.addRequestHeader("x-test", "foo");
            try {
                int status = client.executeMethod(request);
                assertEquals("should return 200", 200, status);
            } finally {
                request.releaseConnection();
            }
        }
    });
}

From source file:com.kodokux.github.api.GithubApiUtil.java

@NotNull
public static Collection<String> getTokenScopes(@NotNull GithubAuthData auth) throws IOException {
    HttpMethod method = null;
    try {/*from ww w.j  a  va2  s.c  o m*/
        String uri = GithubUrlUtil.getApiUrl(auth.getHost()) + "/user";
        method = doREST(auth, uri, null, Collections.<Header>emptyList(), HttpVerb.HEAD);

        checkStatusCode(method);

        Header header = method.getResponseHeader("X-OAuth-Scopes");
        if (header == null) {
            throw new HttpException("No scopes header");
        }

        Collection<String> scopes = new ArrayList<String>();
        for (HeaderElement elem : header.getElements()) {
            scopes.add(elem.getName());
        }
        return scopes;
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Execute method with httpClient, do not follow 30x redirects.
 *
 * @param httpClient Http client instance
 * @param method     Http method/*from   w w w.  java 2s . c  om*/
 * @return status
 * @throws IOException on error
 */
public static int executeNoRedirect(HttpClient httpClient, HttpMethod method) throws IOException {
    int status;
    try {
        status = httpClient.executeMethod(method);
        // check NTLM
        if ((status == HttpStatus.SC_UNAUTHORIZED || status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED)
                && acceptsNTLMOnly(method) && !hasNTLM(httpClient)) {
            LOGGER.debug("Received " + status + " unauthorized at " + method.getURI() + ", retrying with NTLM");
            resetMethod(method);
            addNTLM(httpClient);
            status = httpClient.executeMethod(method);
        }
    } finally {
        method.releaseConnection();
    }
    // caller will need to release connection
    return status;
}