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.encuestame.core.util.SocialUtils.java

/**
 * Short URL with bitly.com./*from   w w w  . j a v a 2  s.c om*/
 * @param urlPath url
 * @param key bitly key
 * @param login bitly login
 * @return
 */
public static String getBitLy(final String urlPath, final String key, final String login) {
    final HttpClient httpclient = new HttpClient();
    final HttpMethod method = new GetMethod(SocialUtils.BITLY_SHORT_URL);
    method.setQueryString(
            new NameValuePair[] { new NameValuePair("longUrl", urlPath), new NameValuePair("version", "2.0.1"),
                    new NameValuePair("login", login), new NameValuePair("apiKey", key),
                    new NameValuePair("format", "json"), new NameValuePair("history", "1") });
    String responseXml = null;
    try {
        httpclient.executeMethod(method);
        //{"errorCode": 0, "errorMessage": "",
        //"results": {"http://www.encuestame.org": {"userHash": "gmks0X", "shortKeywordUrl": "", "hash": "hMMQuX",
        // "shortCNAMEUrl": "http://bit.ly/gmks0X", "shortUrl": "http://bit.ly/gmks0X"}},
        //"statusCode": "OK"}
        final Object jsonObject = JSONValue.parse(method.getResponseBodyAsString());
        log.debug("getBitLy: " + jsonObject.toString());
        final JSONObject o = (JSONObject) jsonObject;
        final JSONObject results = (JSONObject) o.get("results");
        final JSONObject url = (JSONObject) results.get(urlPath);
        responseXml = (String) url.get("shortUrl");
    } catch (HttpException e1) {
        log.error(e1);
        responseXml = urlPath;
    } catch (IOException e1) {
        log.error(e1);
        responseXml = urlPath;
    } catch (Exception e) {
        log.error(e);
        responseXml = urlPath;
    }
    return responseXml;
}

From source file:org.everit.jira.updatenotifier.TimetrackerVersionUpdater.java

private synchronized void update() {
    if (!updateRequired()) {
        return;/*from   w  w w.j  av  a  2s. com*/
    }
    updateNotifier.putLastUpdateTime(System.currentTimeMillis());
    HttpClient httpClient = new HttpClient();
    HttpMethod method = new GetMethod(
            MARKETPLACE_URL_FIRST_PART + buildNumber + MARKETPLACE_URL_WITH_VERSION_PARAMETER);
    method.addRequestHeader("accept", "application/json");
    String response;
    try {
        int statusCode = httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            throw new UpdateException("Update JTTP latest version failed. Status code is : " + statusCode
                    + "Response body is: " + method.getResponseBodyAsString());
        }
        response = method.getResponseBodyAsString();
    } catch (IOException e) {
        throw new UpdateException("Update JTTP latest version failed. ", e);
    }
    Gson gson = new Gson();
    JiraMarketplaceJSONDTO fromJson = gson.fromJson(response, JiraMarketplaceJSONDTO.class);
    String latestVersion = fromJson.getEmbedded().getVersion().getName();
    updateNotifier.putLatestVersion(latestVersion);
}

From source file:org.executequery.http.spi.DefaultRemoteHttpClient.java

private RemoteHttpResponse executeMethod(HttpMethod method, HttpClient client) {

    try {/*from ww  w . j a va 2 s.  co m*/

        int statusCode = client.executeMethod(method);

        return new RemoteHttpResponse(statusCode, method.getResponseBodyAsString());

    } catch (HttpException e) {

        throw new RemoteHttpClientException(e);

    } catch (IOException e) {

        throw new RemoteHttpClientException(e);
    }

}

From source file:org.exoplatform.bonitaextension.connectors.webdav.common.WebDAVClient.java

/**
 * To delete either a folder or a file//from  w  w w  .  j ava 2 s.c o  m
 *
 * @param uri
 * @throws Exception
 */
/* NOT TESTED
public WebDAVResponse deleteItem(String uri) throws Exception {
   if (LOGGER.isLoggable(Level.INFO)) {
 LOGGER.info("deleteItem '" + uri +"'");
   }
        
   DeleteMethod httpMethod = new DeleteMethod(uri);
   client.executeMethod(httpMethod);
        
   WebDAVResponse objResponse = processResponse(httpMethod, true);
   httpMethod.releaseConnection();
   return objResponse;
}
        
*/

/* NOT TESTED
public WebDAVResponse checkout(String uri) throws Exception {
        
   if (LOGGER.isLoggable(Level.INFO)) {
 LOGGER.info("checkout '" + uri +"'");
   }
        
   CheckoutMethod httpMethod = new CheckoutMethod(uri);
   client.executeMethod(httpMethod);
        
   WebDAVResponse objResponse = processResponse(httpMethod, true);
   httpMethod.releaseConnection();
   return objResponse;
}
 */

/* NOT TESTED
public WebDAVResponse checkin(String uri) throws Exception {
        
   if (LOGGER.isLoggable(Level.INFO)) {
 LOGGER.info("checkin '" + uri +"'");
   }
        
   CheckinMethod httpMethod = new CheckinMethod(uri);
   client.executeMethod(httpMethod);
        
   WebDAVResponse objResponse = processResponse(httpMethod, true);
   httpMethod.releaseConnection();
   return objResponse;
}
*/

/* NOT TESTED
        
public WebDAVResponse cancelCheckout(String uri) throws Exception {
        
   if (LOGGER.isLoggable(Level.INFO)) {
 LOGGER.info("cancelCheckout '" + uri +"'");
   }
        
   UncheckoutMethod httpMethod = new UncheckoutMethod(uri);
   client.executeMethod(httpMethod);
        
   WebDAVResponse objResponse = processResponse(httpMethod, true);
   httpMethod.releaseConnection();
   return objResponse;
}
*/

/* NOT TESTED
public WebDAVResponse report(String uri) throws Exception {
        
   if (LOGGER.isLoggable(Level.INFO)) {
 LOGGER.info("report '" + uri +"'");
   }
        
   ReportInfo reportInfo = new ReportInfo(ReportType.VERSION_TREE);
        
   ReportMethod httpMethod = new ReportMethod(uri, reportInfo);
   client.executeMethod(httpMethod);
        
   WebDAVResponse objResponse = processResponse(httpMethod, false);
        
   MultiStatus multiStatus = httpMethod.getResponseBodyAsMultiStatus();
   MultiStatusResponse responses[] = multiStatus.getResponses();
        
   String responseAsString = "";
   for (int i = 0; i < responses.length; i++) {
 responseAsString += responses[i].getHref() + "\n";
   }
        
   objResponse.setResponse(responseAsString);
   httpMethod.releaseConnection();
   return objResponse;
}
*/
/* NOT TESTED
public WebDAVResponse versionControl(String uri) throws Exception {
        
   if (LOGGER.isLoggable(Level.INFO)) {
 LOGGER.info("versionControl '" + uri +"'");
   }
        
   VersionControlMethod httpMethod = new VersionControlMethod(uri);
   client.executeMethod(httpMethod);
        
   WebDAVResponse objResponse = processResponse(httpMethod, true);
   httpMethod.releaseConnection();
   return objResponse;
}
*/

private WebDAVResponse processResponse(HttpMethod httpMethod, boolean getResponseAsString) {

    String statusCode = "-1";
    if (httpMethod.getStatusCode() > 0) {
        statusCode = String.valueOf(httpMethod.getStatusCode());
    }
    String statusText = httpMethod.getStatusText();

    String responseString = "";
    if (getResponseAsString) {
        try {
            responseString = httpMethod.getResponseBodyAsString();
            if (responseString == null) {
                responseString = "";
            }
        } catch (IOException e) {
            if (LOGGER.isLoggable(Level.WARNING)) {
                LOGGER.warning("IOException while getting responseAsString: " + e.getMessage());
            }
            e.printStackTrace();
        }
    }

    if (LOGGER.isLoggable(Level.INFO)) {
        LOGGER.info("status CODE: " + statusCode + ", status TEXT: " + statusText + "\n");
    }

    WebDAVResponse response = new WebDAVResponse(statusCode, statusText, responseString);
    return response;
}

From source file:org.fao.geonet.services.publisher.GeoServerRest.java

/**
 * //  www.  jav  a2  s  . c  o m
 * @param method
 *            e.g. 'POST', 'GET', 'PUT' or 'DELETE'
 * @param urlParams
 *            REST API parameter
 * @param postData
 *            XML data
 * @param file
 *            File to upload
 * @param contentType
 *            type of content in case of post data or file updload.
 * @param saveResponse
 * @return
 * @throws IOException
 */
public int sendREST(String method, String urlParams, String postData, File file, String contentType,
        Boolean saveResponse) throws IOException {

    response = "";
    final HttpClient c = httpClientFactory.newHttpClient();
    String url = this.restUrl + urlParams;
    if (Log.isDebugEnabled(LOGGER_NAME)) {
        Log.debug(LOGGER_NAME, "url:" + url);
        Log.debug(LOGGER_NAME, "method:" + method);
        Log.debug(LOGGER_NAME, "postData:" + postData);
    }

    HttpMethod m;
    if (method.equals(METHOD_PUT)) {
        m = new PutMethod(url);
        if (file != null) {
            ((PutMethod) m).setRequestEntity(new InputStreamRequestEntity(new FileInputStream(file)));
        }
        if (postData != null) {
            ((PutMethod) m).setRequestEntity(new StringRequestEntity(postData, contentType, "UTF-8"));
        }
    } else if (method.equals(METHOD_DELETE)) {
        m = new DeleteMethod(url);
    } else if (method.equals(METHOD_POST)) {
        m = new PostMethod(url);
        if (postData != null) {
            ((PostMethod) m).setRequestEntity(new StringRequestEntity(postData, contentType, "UTF-8"));
        }

    } else {
        m = new GetMethod(url);
    }

    if (contentType != null && !"".equals(contentType)) {
        m.setRequestHeader("Content-type", contentType);
    }

    m.setDoAuthentication(true);

    status = c.executeMethod(m);
    if (Log.isDebugEnabled(LOGGER_NAME))
        Log.debug(LOGGER_NAME, "status:" + status);
    if (saveResponse)
        this.response = m.getResponseBodyAsString();

    return status;
}

From source file:org.geoserver.gss.HTTPGSSClient.java

/**
 * Executes the http method, checks the response status, parses the response and returns it.
 * Will throw an exception in case of communication errors, error codes, or service exceptions
 * //from ww w  .j  a  v a 2  s .c  om
 * @throws IOException
 */
Object executeMethod(HttpMethod method) throws IOException {
    Object response;
    try {
        if (LOGGER.isLoggable(Level.FINE)) {
            if (method instanceof GetMethod) {
                GetMethod gm = (GetMethod) method;
                LOGGER.fine("Sending GET request:\n " + method.getURI());
            } else if (method instanceof PostMethod) {
                PostMethod pm = (PostMethod) method;
                XMLEntity entity = (XMLEntity) pm.getRequestEntity();
                String request = entity.toString();
                LOGGER.fine("Sending POST request:\n " + method.getURI() + "\n" + request);
                // ugly, but Encoder cannot be reused, so we have to set a new entity
                // that uses the already generated string
                pm.setRequestEntity(new StringRequestEntity(request, "text/xml", "UTF-8"));
            } else {
                LOGGER.fine("Sending unknown method type : " + method);
            }
        }

        // plain execution
        int statusCode = client.executeMethod(method);

        // check the HTTP status
        if (statusCode != HttpStatus.SC_OK) {
            throw new IOException("HTTP client returned with code " + statusCode);
        }

        // parse the response
        Parser parser = new Parser(configuration);
        parser.setStrict(true);
        parser.setFailOnValidationError(true);
        InputStream is;
        if (LOGGER.isLoggable(Level.FINE)) {
            String responseString = method.getResponseBodyAsString();
            LOGGER.log(Level.FINE, "Response from Unit:\n" + responseString);
            is = new ByteArrayInputStream(responseString.getBytes());
        } else {
            is = method.getResponseBodyAsStream();
        }
        response = parser.parse(is);
    } catch (Exception e) {
        throw (IOException) new IOException("Error occurred while executing " + "a call to the Unit")
                .initCause(e);
    } finally {
        method.releaseConnection();
    }

    // convert a service exception into an IOException if necessary
    if (response instanceof ExceptionReportType) {
        ExceptionReportType report = (ExceptionReportType) response;
        StringBuilder sb = new StringBuilder("The Unit service reported a failure: ");
        for (Iterator it = report.getException().iterator(); it.hasNext();) {
            ExceptionType et = (ExceptionType) it.next();
            for (Iterator eit = et.getExceptionText().iterator(); eit.hasNext();) {
                String text = (String) eit.next();
                sb.append(text);
                if (eit.hasNext())
                    sb.append(". ");
            }

        }

        throw new IOException(sb.toString());
    }

    return response;
}

From source file:org.geoserver.security.iride.service.policy.handler.IridePolicyRequestHandler.java

/**
 *
 * @param serverURL/*ww w. ja va 2s .  c  o  m*/
 * @param params
 * @return
 * @throws IOException
 */
public String handleRequest(String serverURL, Map<String, Object> params) throws IOException {
    final String requestXml = this.createPolicyRequestXml(params);
    final HttpMethod requestHttpMethod = this.createPolicyRequestMethod(requestXml, serverURL);

    String result = "";
    try {
        final int responseCode = this.getHttpClient().executeMethod(requestHttpMethod);
        final String responseXml = requestHttpMethod.getResponseBodyAsString();

        if (responseCode == HttpStatus.SC_OK) {
            result = responseXml;
        } else {
            LOGGER.warn("IRIDE error response code: {} {}", responseCode,
                    HttpStatus.getStatusText(responseCode));
        }

        LOGGER.trace("IRIDE SOAP response: " + responseXml);

        return result;
    } finally {
        requestHttpMethod.releaseConnection();
    }
}

From source file:org.geotools.data.couchdb.client.CouchDBClient.java

/**
 * //from w ww  . jav a  2 s .  c  om
 * @param method
 * @return
 * @throws IOException
 */
private CouchDBResponse executeMethod(HttpMethod method) throws IOException {
    IOException expected = null;
    int result = -1;
    try {
        result = httpClient.executeMethod(method);
    } catch (IOException ex) {
        expected = ex;
    }
    CouchDBResponse resp = new CouchDBResponse(method, result, expected);
    if (logger.isLoggable(Level.FINEST)) {
        logger.finest("Request to : " + method.getPath());
        logger.finest("Response status : " + result);
        logger.finest("Response body:\n" + method.getResponseBodyAsString());
    }
    return resp;
}

From source file:org.httpobjects.tck.IntegrationTest.java

private void assertResource(HttpMethod method, String expectedBody, int expectedResponseCode,
        HeaderSpec... header) {//w w w  .  j  a  v  a 2s  . com
    try {
        HttpClient client = new HttpClient();
        int response = client.executeMethod(method);

        Assert.assertEquals(expectedResponseCode, response);
        if (expectedBody != null)
            Assert.assertEquals(expectedBody, method.getResponseBodyAsString());

        if (header != null) {
            for (HeaderSpec next : header) {
                Header h = method.getResponseHeader(next.name);
                Assert.assertNotNull("Expected a \"" + next.name + "\" value of \"" + next.value + "\"", h);
                Assert.assertEquals(next.value, h.getValue());
            }
        }
    } catch (HttpException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.iavante.sling.commons.services.CopyAndRenameOperationIT.java

public void test_copy_and_rename() {

    try {/*from  w  w w  .ja  v a 2 s .com*/
        Thread.sleep(2000);
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }

    PostMethod post_copyandrename = new PostMethod(
            SLING_URL + COLLECTIONS_URL + slug_collection + "/" + SOURCES_FOLDER + "/" + source_title);
    post_copyandrename.setDoAuthentication(true);

    String dest = COLLECTIONS_URL + slug_collection + "/" + CONTENTS_FOLDER + "/" + slug_content1 + "/"
            + SOURCES_FOLDER + "/" + source_dest_slug;

    NameValuePair[] data_copy = { new NameValuePair(":operation", "copyandrename"),
            new NameValuePair(":dest", dest) };

    post_copyandrename.setRequestBody(data_copy);
    try {
        client.executeMethod(post_copyandrename);
    } catch (HttpException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    post_copyandrename.releaseConnection();

    // Create another content in collection       
    try {
        Thread.sleep(4000);
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }

    HttpMethod get_content = new GetMethod(SLING_URL + dest + "/file");

    try {
        this.client.executeMethod(get_content);
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // handle response.   
    String response_body = "";
    try {
        response_body = get_content.getResponseBodyAsString();
    } catch (IOException e) {
        e.printStackTrace();
    }

    assertEquals(response_body, source_file);
    get_content.releaseConnection();

    HttpMethod get_content_title = new GetMethod(SLING_URL + dest + "/title");

    try {
        this.client.executeMethod(get_content_title);
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // handle response.   
    response_body = "";
    try {
        response_body = get_content_title.getResponseBodyAsString();
    } catch (IOException e) {
        e.printStackTrace();
    }

    assertEquals(response_body, source_dest_title);
    get_content.releaseConnection();

    // Bad operation
    PostMethod post_copyandrename_bad = new PostMethod(
            SLING_URL + COLLECTIONS_URL + slug_collection + "/" + SOURCES_FOLDER);
    dest = COLLECTIONS_URL + slug_collection + "/" + CONTENTS_FOLDER + "/" + slug_content1 + "/"
            + SOURCES_FOLDER + "/" + source_dest_slug;

    NameValuePair[] data_copy_bad = { new NameValuePair(":operation", "copyandrename"),
            new NameValuePair(":dest", dest) };

    post_copyandrename_bad.setRequestBody(data_copy_bad);
    try {
        client.executeMethod(post_copyandrename_bad);
    } catch (HttpException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    assertEquals(post_copyandrename_bad.getStatusCode(), 412);
    post_copyandrename_bad.releaseConnection();
}