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:com.tribune.uiautomation.testscripts.Photo.java

public static Photo find(String namespace, String slug) throws JSONException {
    if (namespace == null || slug == null) {
        return null;
    }/*www  . ja  v  a  2s  . c  om*/
    GetMethod get = new GetMethod(constructResourceUrl(namespace, slug));
    setRequestHeaders(get);
    Photo photo = null;

    try {
        HttpClient client = new HttpClient();
        int status = client.executeMethod(get);

        log.debug("Photo Service find return status: " + get.getStatusLine());

        if (status == HttpStatus.SC_OK) {
            photo = new Photo();
            processResponse(photo, get.getResponseBodyAsStream());
            photo.setPersisted(true);
        }
    } catch (HttpException e) {
        log.fatal("Fatal protocol violation: " + e.getMessage(), e);
    } catch (IOException e) {
        log.fatal("Fatal transport error: " + e.getMessage(), e);
    } finally {
        // Release the connection.
        get.releaseConnection();
    }

    return photo;
}

From source file:com.agile_coder.poker.server.stories.steps.BaseSteps.java

protected String getStatus(int session) throws IOException {
    HttpClient client = new HttpClient();
    GetMethod get = new GetMethod(BASE_URL + "/" + session + "/status");
    int result;/*from   w ww . ja va2  s.  com*/
    String response;
    try {
        client.executeMethod(get);
        result = get.getStatusCode();
        response = get.getResponseBodyAsString();
    } finally {
        get.releaseConnection();
    }
    assertEquals(HttpStatus.SC_OK, result);
    return response;
}

From source file:com.isencia.passerelle.model.util.RESTFacade.java

/**
 * Get all flow handles from a Passerelle Manager server instance.
 * The baseURL should identify the REST service, i.e. be of the form :
 * <code>http://localhost:8080/PasserelleManagerService/V1.0</code>.
 * /*from   www  .  j  a va 2 s.  c o  m*/
 * <br/>
 * For "legacy" compatibility, also <code>http://localhost:8080/PasserelleManagerService/V1.0/jobs</code>
 * is still supported, but discouraged.
 * 
 * @param baseURL should be not-null or an NPE will be thrown!
 * @return
 * @throws PasserelleException
 */
public Collection<FlowHandle> getAllRemoteFlowHandles(URL baseURL) throws PasserelleException {
    String baseURLStr = baseURL.toString();

    if (!baseURLStr.endsWith("jobs")) {
        baseURLStr += "/jobs";
    }
    String jobHeadersResponse = invokeMethodForURL(new GetMethod(baseURLStr));
    if (jobHeadersResponse != null) {
        Collection<FlowHandle> flowHandles = buildFlowHandles(jobHeadersResponse);
        return flowHandles;
    } else {
        return new ArrayList<FlowHandle>(0);
    }
}

From source file:io.sightly.tck.http.Client.java

/**
 * Retrieves the content available at {@code url} as a {@link String}. The server must respond with a status code equal to {@code
 * expectedStatusCode}, otherwise this method will throw a {@link ClientException};
 *
 * @param url                the URL from which to retrieve the content
 * @param expectedStatusCode the expected status code from the server
 * @return the content, as a {@link String}
 * @throws ClientException if the server's status code differs from the {@code expectedStatusCode} or if any other error is encountered
 *///from   w  w  w . j  a v  a  2s .c o m
public String getStringContent(String url, int expectedStatusCode) {
    GetMethod method = new GetMethod(url);
    try {
        int statusCode = client.executeMethod(method);
        if (statusCode == expectedStatusCode) {
            InputStream is = method.getResponseBodyAsStream();
            return IOUtils.toString(is, "UTF-8");
        } else {
            throw new ClientException(String.format("Received status code %d, expected %d - url %s", statusCode,
                    expectedStatusCode, url));
        }
    } catch (IOException e) {
        throw new ClientException("Unable to complete request to " + url, e);
    }
}

From source file:com.example.listsync.WebDavRepository.java

private List<String> doDownload(String file) throws IOException {
    LOGGER.info("downloading {}", file);
    GetMethod get = new GetMethod(getFullWatchURL() + file);
    int i = client.executeMethod(get);
    if (i != 200) {
        return new ArrayList<>();
    }/*from   w  w w .ja v  a2 s . co m*/
    byte[] bytes = get.getResponseBody();
    LOGGER.info("download complete {}", file);
    return IOUtils.readLines(new ByteArrayInputStream(bytes));
}

From source file:com.lyncode.jtwig.acceptance.AbstractJtwigAcceptanceTest.java

protected GetMethod serverReceivesGetRequest(String relativeUrl) throws IOException {
    getResult = new GetMethod("http://localhost:" + thePort() + relativeUrl);
    httpClient.executeMethod(getResult);

    getResult.getResponseBodyAsString();
    return getResult;
}

From source file:com.sun.syndication.propono.atom.client.EntryIterator.java

private void getNextEntries() throws ProponoException {
    if (nextURI == null)
        return;//from  w  ww .j a v a2s.com
    GetMethod colGet = new GetMethod(collection.getHrefResolved(nextURI));
    collection.addAuthentication(colGet);
    try {
        collection.getHttpClient().executeMethod(colGet);
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(colGet.getResponseBodyAsStream());
        WireFeedInput feedInput = new WireFeedInput();
        col = (Feed) feedInput.build(doc);
    } catch (Exception e) {
        throw new ProponoException("ERROR: fetching or parsing next entries, HTTP code: "
                + (colGet != null ? colGet.getStatusCode() : -1), e);
    } finally {
        colGet.releaseConnection();
    }
    members = col.getEntries().iterator();
    offset += col.getEntries().size();

    nextURI = null;
    List altLinks = col.getOtherLinks();
    if (altLinks != null) {
        Iterator iter = altLinks.iterator();
        while (iter.hasNext()) {
            Link link = (Link) iter.next();
            if ("next".equals(link.getRel())) {
                nextURI = link.getHref();
            }
        }
    }
}

From source file:eu.learnpad.core.impl.or.XwikiCoreFacadeRestResource.java

@Override
public InputStream getModel(String modelSetId, ModelSetType type) throws LpRestException {
    // Now send the package's path to the importer for XWiki
    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/or/corefacade/getmodel/%s", DefaultRestResource.REST_URI,
            modelSetId);/*  www.j ava  2 s  .c  o m*/
    GetMethod getMethod = new GetMethod(uri);
    getMethod.addRequestHeader("Accept", "application/xml");

    NameValuePair[] queryString = new NameValuePair[1];
    queryString[0] = new NameValuePair("type", type.toString());
    getMethod.setQueryString(queryString);

    InputStream model = null;
    try {
        httpClient.executeMethod(getMethod);
        model = getMethod.getResponseBodyAsStream();
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }
    return model;
}

From source file:edu.unc.lib.dl.fedora.FedoraAccessControlService.java

/**
 * @Inheritdoc//w  ww. jav a 2s  . co m
 * 
 *             Retrieves the access control from a Fedora JSON endpoint, represented by role to group relations.
 */
@SuppressWarnings("unchecked")
@Override
public ObjectAccessControlsBean getObjectAccessControls(PID pid) {
    GetMethod method = new GetMethod(this.aclEndpointUrl + pid.getPid() + "/getAccess");
    try {
        int statusCode = httpClient.executeMethod(method);

        if (statusCode == HttpStatus.SC_OK) {
            Map<?, ?> result = (Map<?, ?>) mapper.readValue(method.getResponseBodyAsStream(), Object.class);
            Map<String, List<String>> roles = (Map<String, List<String>>) result.get("roles");
            Map<String, List<String>> globalRoles = (Map<String, List<String>>) result.get("globals");
            List<String> embargoes = (List<String>) result.get("embargoes");
            List<String> publicationStatus = (List<String>) result.get("publicationStatus");
            List<String> objectState = (List<String>) result.get("objectState");

            return new ObjectAccessControlsBean(pid, roles, globalRoles, embargoes, publicationStatus,
                    objectState);
        }
    } catch (HttpException e) {
        log.error("Failed to retrieve object access control for " + pid, e);
    } catch (IOException e) {
        log.error("Failed to retrieve object access control for " + pid, e);
    } finally {
        method.releaseConnection();
    }

    return null;
}

From source file:net.oauth.client.httpclient3.HttpClient3.java

public HttpResponseMessage execute(HttpMessage request, Map<String, Object> parameters) throws IOException {
    final String method = request.method;
    final String url = request.url.toExternalForm();
    final InputStream body = request.getBody();
    final boolean isDelete = DELETE.equalsIgnoreCase(method);
    final boolean isPost = POST.equalsIgnoreCase(method);
    final boolean isPut = PUT.equalsIgnoreCase(method);
    byte[] excerpt = null;
    HttpMethod httpMethod;/*  w w  w.  j a va 2  s .c om*/
    if (isPost || isPut) {
        EntityEnclosingMethod entityEnclosingMethod = isPost ? new PostMethod(url) : new PutMethod(url);
        if (body != null) {
            ExcerptInputStream e = new ExcerptInputStream(body);
            String length = request.removeHeaders(HttpMessage.CONTENT_LENGTH);
            entityEnclosingMethod.setRequestEntity((length == null) ? new InputStreamRequestEntity(e)
                    : new InputStreamRequestEntity(e, Long.parseLong(length)));
            excerpt = e.getExcerpt();
        }
        httpMethod = entityEnclosingMethod;
    } else if (isDelete) {
        httpMethod = new DeleteMethod(url);
    } else {
        httpMethod = new GetMethod(url);
    }
    for (Map.Entry<String, Object> p : parameters.entrySet()) {
        String name = p.getKey();
        String value = p.getValue().toString();
        if (FOLLOW_REDIRECTS.equals(name)) {
            httpMethod.setFollowRedirects(Boolean.parseBoolean(value));
        } else if (READ_TIMEOUT.equals(name)) {
            httpMethod.getParams().setIntParameter(HttpMethodParams.SO_TIMEOUT, Integer.parseInt(value));
        }
    }
    for (Map.Entry<String, String> header : request.headers) {
        httpMethod.addRequestHeader(header.getKey(), header.getValue());
    }
    HttpClient client = clientPool.getHttpClient(new URL(httpMethod.getURI().toString()));
    client.executeMethod(httpMethod);
    return new HttpMethodResponse(httpMethod, excerpt, request.getContentCharset());
}