Example usage for org.apache.commons.httpclient.methods GetMethod GetMethod

List of usage examples for org.apache.commons.httpclient.methods GetMethod GetMethod

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods GetMethod GetMethod.

Prototype

public GetMethod(String uri) 

Source Link

Usage

From source file:de.mpg.escidoc.services.util.SchematronUtil.java

public static boolean isChild(String ou) throws Exception {
    if (ou != null) {
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(PropertyReader.getProperty("escidoc.framework_access.framework.url")
                + "/oum/organizational-unit/" + ou.trim() + "/resources/path-list");
        try {/*from w ww. j ava  2s.  com*/
            httpClient.executeMethod(getMethod);
            if (getMethod.getStatusCode() == 200) {
                if (getMethod.getResponseBodyAsString().contains("\"/oum/organizational-unit/"
                        + PropertyReader.getProperty("escidoc.pubman.root.organisation.id") + "\"")) {
                    return true;
                } else {
                    return false;
                }
            } else {
                LOGGER.warn("Error while checking organizational-unit path: Return code "
                        + getMethod.getStatusCode() + "\n" + getMethod.getResponseBodyAsString());
                return false;
            }
        } catch (IllegalArgumentException e) {
            LOGGER.warn("Error while checking organizational-unit path: " + e.getMessage());
            LOGGER.debug("Error", e);
            return false;
        }
    } else {
        return false;
    }
}

From source file:de.mpg.imeji.presentation.lang.Iso639_1Helper.java

private String getVocabularyString() {
    try {//from  w  w w . ja  va  2 s  .co m
        HttpClient client = new HttpClient();
        GetMethod getMethod = new GetMethod(
                PropertyReader.getProperty("escidoc.cone.isos639_1.all") + "?format=options");
        client.executeMethod(getMethod);
        return getMethod.getResponseBodyAsString();
    } catch (Exception e) {
        logger.error("Couldn't read ISO639_1 vocabulary, will use default one! Error: " + e);
        return "en|en - English\nde|de - German";
    }
}

From source file:idea.clientRequests.httpClientRequester.java

public boolean doHttpget(String csUrl) {
    boolean bStatus = false;
    m_responseBody = null;// w  ww  . ja  v a  2 s. c o  m
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(csUrl);

    // Provide custom retry handler is necessary
    DefaultHttpMethodRetryHandler handler = new DefaultHttpMethodRetryHandler(3, false);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, handler);
    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }
        // Read the response body.
        m_responseBody = method.getResponseBody();

        bStatus = true;
    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return bStatus;
}

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

/**
 * Appends response form URL to a StringBuffer
 * /*from   w  ww.j  ava 2  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:io.aos.protocol.http.commons.CommonsHttpClient.java

public static void get(String url) {

    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(url);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    try {/*from   ww w . j av a  2  s  . com*/
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("Method failed: " + method.getStatusLine());
        }
        byte[] responseBody = method.getResponseBody();
        LOG.debug(new String(responseBody, "UTF-8"));
    } catch (HttpException e) {
        LOG.error("Fatal protocol violation: " + e.getMessage(), e);
    } catch (IOException e) {
        LOG.error("Fatal transport error: " + e.getMessage(), e);
    } finally {
        method.releaseConnection();
    }

}

From source file:atg.taglib.json.Helper.java

/**
 * Get a response from the server for a test
 *
 * @param pTestUrl The test url, relative to the tests context root
 * @return the <code>ResponseData</code> object for this test
 * @throws IOException //from  www  . j a v a  2s .  c  o m
 * @throws HttpException 
 * @throws JSONException 
 */
public static ResponseData getData(String pType, int pTestNum)
        throws HttpException, IOException, JSONException {
    // Setup HTTP client
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(getTestUrl(pType, pTestNum));

    // Execute the GET request, capturing response status
    int statusCode = client.executeMethod(method);
    String responseBody = method.getResponseBodyAsString();
    method.releaseConnection();

    // Create response data object
    ResponseData data = new ResponseData();
    data.body = responseBody.trim();
    data.statusCode = statusCode;
    if (statusCode == HttpStatus.SC_OK) {
        // Parse the JSON response
        data.json = parseJsonTextToObject(responseBody);
    }

    // Get the expected result
    method = new GetMethod(getStatus200ResultUrl(pType, pTestNum));
    data.expectedStatusCode = HttpStatus.SC_OK;

    // Execute the GET request, capturing response status
    statusCode = client.executeMethod(method);

    if (statusCode == HttpStatus.SC_NOT_FOUND) {
        // Test result wasn't found - we must be expecting an error for this test
        method.releaseConnection();
        method = new GetMethod(getStatus500ResultUrl(pType, pTestNum));
        statusCode = client.executeMethod(method);
        data.expectedStatusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
    }

    responseBody = method.getResponseBodyAsString().trim();
    method.releaseConnection();

    // Parse the expected data   
    if (data.expectedStatusCode == HttpStatus.SC_OK) {
        // Parse body into JSON object
        data.expectedJson = parseJsonTextToObject(responseBody);
    } else {
        // Exception is expected, set the expected key
        data.expectedMsgKey = responseBody.trim();
    }

    return data;
}

From source file:com.tc.admin.UpdateCheckRequestTest.java

public static String getResponseBody(URL url, HttpClient client) throws ConnectException, IOException {
    GetMethod get = new GetMethod(url.toString());

    get.setFollowRedirects(true);/*  w ww .  jav  a 2s .c  o m*/
    try {
        int status = client.executeMethod(get);
        if (status != HttpStatus.SC_OK) {
            throw new ConnectException(
                    "The http client has encountered a status code other than ok for the url: " + url
                            + " status: " + HttpStatus.getStatusText(status));
        }
        return get.getResponseBodyAsString();
    } finally {
        get.releaseConnection();
    }
}

From source file:com.glaf.core.util.http.CommonsHttpClientUtils.java

/**
 * ??GET// w ww. j  av  a 2s .  c  om
 * 
 * @param url
 *            ??
 * @param encoding
 *            
 * @param dataMap
 *            ?
 * 
 * @return
 */
public static String doGet(String url, String encoding, Map<String, String> dataMap) {
    GetMethod method = null;
    String content = null;
    try {
        method = new GetMethod(url);
        method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, encoding);
        method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + encoding);
        if (dataMap != null && !dataMap.isEmpty()) {
            NameValuePair[] nameValues = new NameValuePair[dataMap.size()];
            int i = 0;
            for (Map.Entry<String, String> entry : dataMap.entrySet()) {
                String name = entry.getKey().toString();
                String value = entry.getValue();
                nameValues[i] = new NameValuePair(name, value);
                i++;
            }
            method.setQueryString(nameValues);
        }
        HttpClient client = new HttpClient();
        int status = client.executeMethod(method);
        if (status == HttpStatus.SC_OK) {
            content = method.getResponseBodyAsString();
        }
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } finally {
        if (method != null) {
            method.releaseConnection();
            method = null;
        }
    }
    return content;
}

From source file:com.zimbra.cs.util.yauth.TokenAuthenticateV1.java

/**
 * @param username/*from  ww  w. ja  va  2 s. co m*/
 * @param passwd
 * @return The token
 */
public static String getToken(String username, String passwd) throws IOException, HttpException {
    GetMethod method = new GetMethod(
            "https://login.yahoo.com/config/pwtoken_get?src=ymsgr&login=" + username + "&passwd=" + passwd);
    int response = HttpClientUtil.executeMethod(method);

    if (response >= 200 && response < 300) {
        String body = method.getResponseBodyAsString();

        HashMap<String, String> map = new HashMap<String, String>();
        map.put("ymsgr", null);

        parseResponseBody(body, map);

        return map.get("ymsgr");
    } else {
        throw new IOException("HTTPClient response: " + response);
    }
}

From source file:com.ibm.stocator.fs.swift.SwiftAPIDirect.java

/**
 * GET object// ww w . ja v a2s . com
 *
 * @param path path to object
 * @param authToken authentication token
 * @param bytesFrom from from
 * @param bytesTo bytes to
 * @return SwiftGETResponse that includes input stream and length
 * @throws IOException if network errors
 */
public static SwiftGETResponse getObject(Path path, String authToken, long bytesFrom, long bytesTo)
        throws IOException {
    GetMethod method = new GetMethod(path.toString());
    method.addRequestHeader(new Header("X-Auth-Token", authToken));
    if (bytesTo > 0) {
        final String rangeValue = String.format("bytes=%d-%d", bytesFrom, bytesTo);
        method.addRequestHeader(new Header(Constants.RANGES_HTTP_HEADER, rangeValue));
    }
    HttpMethodParams methodParams = method.getParams();
    methodParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    methodParams.setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 15000);
    methodParams.setSoTimeout(60000);
    method.addRequestHeader(Constants.USER_AGENT_HTTP_HEADER, Constants.STOCATOR_USER_AGENT);
    final HttpClient client = new HttpClient();
    int statusCode = client.executeMethod(method);
    SwiftInputStreamWrapper httpStream = new SwiftInputStreamWrapper(method);
    SwiftGETResponse getResponse = new SwiftGETResponse(httpStream, method.getResponseContentLength());
    return getResponse;
}