Example usage for org.apache.commons.httpclient HttpMethod getResponseBodyAsString

List of usage examples for org.apache.commons.httpclient HttpMethod getResponseBodyAsString

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod getResponseBodyAsString.

Prototype

public abstract String getResponseBodyAsString() throws IOException;

Source Link

Usage

From source file:org.dspace.ctask.demo.MicrosoftTranslator.java

@Override
protected String translateText(String from, String to, String text) throws IOException {

    log.debug("Performing API call to translate from " + from + " to " + to);

    text = URLEncoder.encode(text, "UTF-8");

    String translatedText = null;

    String url = baseUrl + "?appId=" + apiKey;
    url += "&to=" + to + "&from=" + from + "&text=" + text;

    HttpClient client = new HttpClient();
    HttpMethod hm = new GetMethod(url);
    int code = client.executeMethod(hm);
    log.debug("Response code from API call is " + code);

    if (code == 200) {
        String response = hm.getResponseBodyAsString();
        response = response.replaceAll("<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">",
                "");
        response = response.replaceAll("</string>", "");
        translatedText = response;/*from  www. j  ava  2  s . c  om*/
    }

    return translatedText;
}

From source file:org.dspace.rest.providers.DiscoverProvider.java

public List<?> getEntities(EntityReference ref, Search search) {
    log.info("DiscoverProvider - get_entities");

    List<Object> entities = new ArrayList<Object>();

    try {//from   w  ww  . j  a v a 2s . co m
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(
                ConfigurationManager.getProperty("discovery", "search.server") + "/select");
        log.info("DiscoverProvider method - " + ConfigurationManager.getProperty("discovery", "search.server"));

        log.info("DiscoverProvider search.getRestrictions().length - " + search.getRestrictions().length);
        log.info("DiscoverProvider format - " + format);
        List<NameValuePair> nameValuePairsList = new ArrayList<NameValuePair>();
        if (search.getRestrictions().length > 0) {
            for (int i = 0; i < search.getRestrictions().length; i++) {
                log.info("DiscoverProvider search.getRestrictions()[i].getProperty() - "
                        + search.getRestrictions()[i].getProperty());
                log.info("DiscoverProvider search.getRestrictions()[i].getStringValue() - "
                        + search.getRestrictions()[i].getStringValue());
                if (!"org.apache.catalina.ASYNC_SUPPORTED".equals(search.getRestrictions()[i].getProperty())) {
                    nameValuePairsList.add(new NameValuePair(search.getRestrictions()[i].getProperty(),
                            search.getRestrictions()[i].getStringValue()));
                }
            }
            if ("json".equals(format)) {
                nameValuePairsList.add(new NameValuePair("wt", "json"));
            }
        }

        if (search.getOrders().length > 0) {
            for (int i = 0; i < search.getOrders().length; i++) {
                log.info("DiscoverProvider search.getOrders()[i].getProperty() - "
                        + search.getOrders()[i].getProperty());
                nameValuePairsList.add(new NameValuePair("sort", search.getOrders()[i].getProperty()));
            }
        }

        NameValuePair[] nameValuePairs = new NameValuePair[nameValuePairsList.size()];
        nameValuePairsList.toArray(nameValuePairs);
        method.setQueryString(nameValuePairs);

        client.executeMethod(method);
        String s = method.getResponseBodyAsString();
        //            log.info("DiscoverProvider result string - " + s);

        entities.add(new EntityData(s));

        method.releaseConnection();

    } catch (IOException e) {
        throw new EntityException("Internal server error", "IO error, cannot call solr server", 500);
    }

    return entities;
}

From source file:org.dspace.rest.providers.StatisticsProvider.java

public List<?> getEntities(EntityReference ref, Search search) {
    log.info("StatisticsProvider - get_entities");

    List<Object> entities = new ArrayList<Object>();

    try {/*w  w w . j  av a  2s .com*/
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(
                ConfigurationManager.getProperty("solr-statistics", "server") + "/select");
        log.info(
                "StatisticsProvider method - " + ConfigurationManager.getProperty("solr-statistics", "server"));

        log.info("StatisticsProvider search.getRestrictions().length - " + search.getRestrictions().length);
        log.info("StatisticsProvider format - " + format);
        List<NameValuePair> nameValuePairsList = new ArrayList<NameValuePair>();
        if (search.getRestrictions().length > 0) {
            for (int i = 0; i < search.getRestrictions().length; i++) {
                log.info("StatisticsProvider search.getRestrictions()[i].getProperty() - "
                        + search.getRestrictions()[i].getProperty());
                log.info("StatisticsProvider search.getRestrictions()[i].getStringValue() - "
                        + search.getRestrictions()[i].getStringValue());
                if (!"org.apache.catalina.ASYNC_SUPPORTED".equals(search.getRestrictions()[i].getProperty())) {
                    nameValuePairsList.add(new NameValuePair(search.getRestrictions()[i].getProperty(),
                            search.getRestrictions()[i].getStringValue()));
                }
            }
            if ("json".equals(format)) {
                nameValuePairsList.add(new NameValuePair("wt", "json"));
            }
        }

        if (search.getOrders().length > 0) {
            for (int i = 0; i < search.getOrders().length; i++) {
                log.info("StatisticsProvider search.getOrders()[i].getProperty() - "
                        + search.getOrders()[i].getProperty());
                nameValuePairsList.add(new NameValuePair("sort", search.getOrders()[i].getProperty()));
            }
        }

        NameValuePair[] nameValuePairs = new NameValuePair[nameValuePairsList.size()];
        nameValuePairsList.toArray(nameValuePairs);
        method.setQueryString(nameValuePairs);

        client.executeMethod(method);
        String s = method.getResponseBodyAsString();
        //            log.info("StatisticsProvider result string - " + s);

        entities.add(new EntityData(s));

        method.releaseConnection();

    } catch (IOException e) {
        throw new EntityException("Internal server error", "IO error, cannot call solr server", 500);
    }

    return entities;
}

From source file:org.eclipse.ecf.tests.remoteservice.rest.service.RestServiceTest.java

public void testXMLRequest() {
    String serverUrl = service.getServerUrl();
    HttpClient client = new HttpClient();
    HttpMethod method = new HttpMethodBase(serverUrl + "/test.xml") {
        public String getName() {
            return "GET";
        }//from www  .  j  a  v  a 2 s.co  m
    };
    int responseCode = 0;
    try {
        responseCode = client.executeMethod(method);
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    assertEquals(HttpStatus.SC_OK, responseCode);
    try {
        String body = method.getResponseBodyAsString();
        assertEquals(SimpleRestService.XML_RESPONSE, body);
    } catch (IOException e) {
        e.printStackTrace();
        fail("body was not set correctly");
    }
}

From source file:org.eclipse.ecf.tests.remoteservice.rest.service.RestServiceTest.java

public void testJsonResponse() {
    String serverUrl = service.getServerUrl();
    HttpClient client = new HttpClient();
    HttpMethod method = new HttpMethodBase(serverUrl + "/test.json") {
        public String getName() {
            return "GET";
        }//from  ww w  .j a  v a 2s  .  com
    };
    int responseCode = 0;
    try {
        responseCode = client.executeMethod(method);
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    assertEquals(HttpStatus.SC_OK, responseCode);
    try {
        String body = method.getResponseBodyAsString();
        assertEquals(SimpleRestService.JSON_RESPONSE, body);
    } catch (IOException e) {
        e.printStackTrace();
        fail("body was not set correctly");
    }
}

From source file:org.eclipse.mylyn.internal.web.tasks.WebRepositoryConnector.java

private static String requestResource(String url, HttpClient client, HostConfiguration hostConfiguration,
        HttpMethod method) throws IOException, HttpException {
    String refreshUrl = null;//w w  w  .j  a  v  a 2s.c om
    try {
        client.executeMethod(hostConfiguration, method);
        //          int statusCode = client.executeMethod(method);
        //         if (statusCode == 300 || statusCode == 301 || statusCode == 302 || statusCode == 303 || statusCode == 307) {
        //            Header location = method.getResponseHeader("Location");
        //            if (location != null) {
        //               refreshUrl = location.getValue();
        //               if (!refreshUrl.startsWith("/")) {
        //                  refreshUrl = "/" + refreshUrl;
        //               }
        //            }
        //         }

        refreshUrl = getRefreshUrl(url, method);
        if (refreshUrl == null) {
            return method.getResponseBodyAsString();
        }
    } finally {
        method.releaseConnection();
    }

    method = new GetMethod(refreshUrl);
    try {
        client.executeMethod(hostConfiguration, method);
        return method.getResponseBodyAsString();
    } finally {
        method.releaseConnection();
    }
}

From source file:org.eclipse.orion.server.cf.live.cflauncher.commands.CreateFolderCommand.java

protected ServerStatus executeMethod(HttpMethod method) throws HttpException, IOException, JSONException {
    try {//  ww w.  j a  v  a 2 s . c om
        int code = CFActivator.getDefault().getHttpClient().executeMethod(method);

        if (code == 204) {
            /* no content response */
            return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK);
        }

        JSONObject result = new JSONObject();
        result.put("response", method.getResponseBodyAsString());

        if (code != 200 && code != 201) {
            // TODO parse error from XML and put in description
            return HttpUtil.createErrorStatus(Status.ERROR, Integer.toString(code), method.getStatusText());
        }

        return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result);
    } finally {
        /* ensure connections are released back to the connection manager */
        method.releaseConnection();
    }
}

From source file:org.eclipse.orion.server.cf.utils.HttpUtil.java

public static ServerStatus executeMethod(HttpMethod method) throws HttpException, IOException, JSONException {

    try {//from   w w  w  .  jav a 2s .  com
        int code = CFActivator.getDefault().getHttpClient().executeMethod(method);

        if (code == 204) {
            /* no content response */
            return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK);
        }

        String response = method.getResponseBodyAsString();
        JSONObject result;

        try {
            result = new MagicJSONObject(response);
        } catch (JSONException e) {
            result = new JSONObject();
            result.put("response", response);
        }

        if (code != 200 && code != 201) {
            String desctiption = result.optString("description");
            if (desctiption == null || desctiption.length() == 0) {
                desctiption = result.optString("response", "Could not connect to host. Error: " + code);
                if (desctiption.length() > 1000) {
                    desctiption = "Could not connect to host. Error: " + code;
                }
            }
            return new ServerStatus(Status.ERROR, code, desctiption, result, null);
        }

        if (result.has("error_code")) {
            return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    result.optString("description"), result, null);
        }

        return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result);

    } finally {
        /* ensure connections are released back to the connection manager */
        method.releaseConnection();
    }
}

From source file:org.eclipse.scada.hd.exporter.http.client.HdHttpClient.java

public List<DataPoint> getData(final String item, final String type, final Date from, final Date to,
        final Integer number) throws Exception {
    final HttpClient client = new HttpClient();
    final HttpMethod method = new GetMethod(
            this.baseUrl + "/" + URLEncoder.encode(item, "UTF-8") + "/" + URLEncoder.encode(type, "UTF-8")
                    + "?from=" + URLEncoder.encode(Utils.isoDateFormat.format(from), "UTF-8") + "&to="
                    + URLEncoder.encode(Utils.isoDateFormat.format(to), "UTF-8") + "&no=" + number);
    client.getParams().setSoTimeout((int) this.timeout);
    try {/*from  w ww  .j av a 2s  .  co  m*/
        final int status = client.executeMethod(method);
        if (status != HttpStatus.SC_OK) {
            throw new RuntimeException("Method failed with error " + status + " " + method.getStatusLine());
        }
        return Utils.fromJson(method.getResponseBodyAsString());
    } finally {
        method.releaseConnection();
    }
}

From source file:org.eclipse.swordfish.internal.resolver.backend.base.impl.HttpClientProxy.java

private ClientResponse doInvoke(ClientRequest request) {
    ClientResponse response = RegistryProxyFactory.getInstance().createResponse();
    HttpMethod method = getMethod(request.getMethod());

    try {/*from   w w  w .  j  a  v  a 2  s  .  c  o  m*/
        String escapedRequestUrl = request.getURI().toASCIIString();
        HttpURL requestUrl = new HttpURL(escapedRequestUrl.toCharArray());
        if (request.getProperties() != null) {
            Map<String, String> properties = request.getProperties();
            String[] queryNames = properties.keySet().toArray(new String[0]);
            String[] queryValues = properties.values().toArray(new String[0]);
            requestUrl.setQuery(queryNames, queryValues);
        }

        method.setURI(requestUrl);
        int statusCode = getClient().executeMethod(method);
        response.setStatus(Status.get(statusCode));

        String responseBody = method.getResponseBodyAsString();
        if (request.getEntityType() != null) {
            response.setEntity(mapResponse(responseBody, request.getEntityType()));
        } else {
            response.setEntity(responseBody);
        }
    } catch (HttpException e) {
        LOG.error("Couldn't perform call to registry: ", e);
        response.setStatus(Status.ERROR);
        response.setEntity(e);
    } catch (IOException e) {
        LOG.error("Couldn't perform call to registry: ", e);
        response.setStatus(Status.ERROR);
        response.setEntity(e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
    return response;
}