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:com.alta189.cyborg.commit.ShortUrlService.java

public static String shorten(String url, String keyword) {
    switch (service) {
    case BIT_LY:/* w  ww  . j a va  2s.  co m*/
        HttpClient httpclient = new HttpClient();
        HttpMethod method = new GetMethod("http://api.bit.ly/shorten");
        method.setQueryString(
                new NameValuePair[] { new NameValuePair("longUrl", url), new NameValuePair("version", "2.0.1"),
                        new NameValuePair("login", user), new NameValuePair("apiKey", apiKey),
                        new NameValuePair("format", "xml"), new NameValuePair("history", "1") });
        try {
            httpclient.executeMethod(method);
            String responseXml = method.getResponseBodyAsString();
            String retVal = null;
            if (responseXml != null) {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                StringReader st = new StringReader(responseXml);
                Document d = db.parse(new InputSource(st));
                NodeList nl = d.getElementsByTagName("shortUrl");
                if (nl != null) {
                    Node n = nl.item(0);
                    retVal = n.getTextContent();
                }
            }

            return retVal;
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
        return null;
    case SPOUT_IN:
        HttpClient client = new HttpClient();
        String result = null;
        client.getParams().setParameter("http.useragent", "Test Client");

        BufferedReader br = null;
        PostMethod pMethod = new PostMethod("http://spout.in/yourls-api.php");
        pMethod.addParameter("signature", apiKey);
        pMethod.addParameter("action", "shorturl");
        pMethod.addParameter("format", "simple");
        pMethod.addParameter("url", url);
        if (keyword != null) {
            pMethod.addParameter("keyword", keyword);
        }

        try {
            int returnCode = client.executeMethod(pMethod);

            if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
                System.err.println("The Post method is not implemented by this URI");
                pMethod.getResponseBodyAsString();
            } else {
                br = new BufferedReader(new InputStreamReader(pMethod.getResponseBodyAsStream()));
                String readLine;
                if (((readLine = br.readLine()) != null)) {
                    result = readLine;
                }
            }
        } catch (Exception e) {
            System.err.println(e);
        } finally {
            pMethod.releaseConnection();
            if (br != null) {
                try {
                    br.close();
                } catch (Exception fe) {
                    fe.printStackTrace();
                }
            }
        }
        return result;
    }
    return null;
}

From source file:com.zimbra.cs.util.WebClientServiceUtil.java

public static String sendServiceRequestToUiNode(Server server, String serviceUrl) throws ServiceException {
    if (isServerAtLeast8dot5(server)) {
        HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
        HttpProxyUtil.configureProxy(client);
        AuthToken authToken = AuthProvider.getAdminAuthToken();
        ZimbraLog.misc.debug("got admin auth token");
        String resp = "";
        HttpMethod method = null;
        try {/* w  ww . ja v  a2s  .  c o  m*/
            method = new GetMethod(URLUtil.getServiceURL(server, serviceUrl, false));
            ZimbraLog.misc.debug("connecting to ui node %s", server.getName());
            method.addRequestHeader(PARAM_AUTHTOKEN, authToken.getEncoded());
            int result = HttpClientUtil.executeMethod(client, method);
            ZimbraLog.misc.debug("resp: %d", result);
            resp = method.getResponseBodyAsString();
            ZimbraLog.misc.debug("got response from ui node: %s", resp);
        } catch (IOException e) {
            ZimbraLog.misc.warn("failed to get response from ui node", e);
        } catch (AuthTokenException e) {
            ZimbraLog.misc.warn("failed to get authToken", e);
        } finally {
            if (method != null) {
                method.releaseConnection();
            }
        }
        if (authToken != null && authToken.isRegistered()) {
            try {
                authToken.deRegister();
                ZimbraLog.misc.debug("de-registered auth token, isRegistered?%s", authToken.isRegistered());
            } catch (AuthTokenException e) {
                ZimbraLog.misc.warn("failed to de-register authToken", e);
            }
        }
        return resp;
    }
    return "";
}

From source file:com.intellij.tasks.impl.httpclient.ResponseUtil.java

public static String getResponseContentAsString(@Nonnull HttpMethod response) throws IOException {
    // Sometimes servers don't specify encoding and HttpMethod#getResponseBodyAsString
    // by default decodes from Latin-1, so we got to read byte stream and decode it from UTF-8
    // manually/*from   ww w . j a v  a2s. c om*/
    //if (!response.hasBeenUsed()) {
    //  return "";
    //}
    org.apache.commons.httpclient.Header header = response.getResponseHeader(HTTP.CONTENT_TYPE);
    if (header != null && header.getValue().contains("charset")) {
        // ISO-8859-1 if charset wasn't specified in response
        return StringUtil.notNullize(response.getResponseBodyAsString());
    } else {
        InputStream stream = response.getResponseBodyAsStream();
        return stream == null ? "" : StreamUtil.readText(stream, DEFAULT_CHARSET);
    }
}

From source file:com.wafersystems.util.HttpUtil.java

/**
 * URL?// w  w w  .j  a  v  a 2 s . c om
 * 
 * @param hClient   HttpClient
 * @param url      URL
 * 
 * @return
 * @throws Exception
 */
public static String openURL(HttpClient hClient, String url) throws Exception {
    HttpMethod method = null;
    try {
        //Get
        method = new GetMethod(url);
        // URL
        int result = hClient.executeMethod(method);
        //cookie?
        //getCookie(method.getURI().getHost(), method.getURI().getPort(), "/" , false , hClient.getState().getCookies());

        //???
        result = checkRedirect(method.getURI().getHost(), method.getURI().getPort(), hClient, method, result);

        if (result != HttpStatus.SC_OK)
            logger.error(method.getPath() + "" + method.getStatusLine().toString() + "\r\n"
                    + method.getResponseBodyAsString());

        return method.getResponseBodyAsString();
    } finally {
        method.releaseConnection();
    }
}

From source file:eu.eco2clouds.api.bonfire.client.rest.RestClient.java

private static Response executeMethod(HttpMethod httpMethod, String type, String username, String password,
        String url) {/*  w  w  w.  jav a2  s .  c  om*/
    HttpClient client = getClient(url, username, password);
    Response response = null;

    // We set the Heathers
    httpMethod.setDoAuthentication(true);
    httpMethod.addRequestHeader(BONFIRE_ASSERTED_ID_HEADER, username);
    //httpMethod.addRequestHeader(BONFIRE_ASSERTED_ID_HEADER, groups);
    httpMethod.addRequestHeader("Accept", type);
    httpMethod.addRequestHeader("Content-Type", type);

    try {
        int statusCode = client.executeMethod(httpMethod);
        String responsePayload = httpMethod.getResponseBodyAsString();
        response = new Response(statusCode, responsePayload);
    } catch (IOException iOException) {
        System.out.println("ERROR TRYING TO PERFORM GET TO: " + httpMethod.getPath());
        System.out.println("ERROR: " + iOException.getMessage());
        System.out.println("ERROR: " + iOException.getStackTrace());
    } finally {
        httpMethod.releaseConnection();
    }

    return response;
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Checks if there is a Javascript redirect inside the page,
 * and returns it.//from w w  w . jav  a 2s  . com
 * <p/>
 * A Javascript redirect is usually found on OTP pre-auth page,
 * when the pre-auth form is in a distinct page from the regular Exchange login one.
 *
 * @param method http method
 * @return the redirect URL if found, or null if no Javascript redirect has been found
 */
private static String getJavascriptRedirectUrl(HttpMethod method) throws IOException {
    String responseBody = method.getResponseBodyAsString();
    String jsRedirectionUrl = null;
    if (responseBody.indexOf("javascript:go_url()") > 0) {
        // Create a pattern to match a javascript redirect url
        Pattern p = Pattern.compile("go_url\\(\\)[^{]+\\{[^l]+location.replace\\(\"(/[^\"]+)\"\\)");
        Matcher m = p.matcher(responseBody);
        if (m.find()) {
            // Javascript redirect found!
            jsRedirectionUrl = m.group(1);
        }
    }
    return jsRedirectionUrl;
}

From source file:jshm.sh.Client.java

/**
 * Login to ScoreHero and retrieve the necessary cookies
 * for subsequent requests that require being logged in.
 * @param userName/*  www  . ja va  2 s  .c o  m*/
 * @param password
 * @param useCache Whether to use the cached results, if possible
 * @return
 * @throws java.io.IOException
 * @throws ClientException
 */
public static Cookie[] getAuthCookies(final String userName, final String password, final boolean useCache)
        throws Exception {
    if (null != cookieCache && useCache)
        return cookieCache;

    Client.username = userName;

    new HttpForm((Object) URLs.LOGIN_URL, "uname", userName, "pass", password, "remember", "1", "submit",
            "Login") {

        @Override
        public void afterSubmit(final int response, final HttpClient client, final HttpMethod method)
                throws Exception {
            HttpForm.LOG.finest("entered getAuthCookies().HttpForm.afterSubmit()");

            Cookie[] cookies = client.getState().getCookies();

            if (response == 302 && checkAuthCookies(cookies, userName)) {
                //               System.out.println("Validated Successfully!");
                method.releaseConnection();
                cookieCache = cookies;
                HttpForm.LOG.finest("exiting getAuthCookies().HttpForm.afterSubmit()");
                return;
            }

            String body = method.getResponseBodyAsString();
            method.releaseConnection();

            try {
                Pattern p = Pattern.compile("<span class=\"error\"[^>]*>(.+?)</span>");
                Matcher m = p.matcher(body);

                if (m.find()) {
                    throw new ClientException(m.group(1));
                }

                LOG.warning("Unhandled login failure, responseCode=" + response + ", response body follows");
                LOG.warning(body);

                throw new ClientException("login failed, unknown error");
            } catch (Exception t) {
                LOG.throwing("Client", "getAuthCookies().HttpClient.afterSubmit()", t);
                throw t;
            }
        }
    }.submit();

    return cookieCache;
}

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//from  www  .  j av a  2s . com
 *
 * @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:com.thoughtworks.go.helpers.HttpClientHelper.java

public String httpRequest(final String path, RequestMethod methodRequired, String params) throws Exception {
    HttpMethod method = doRequest(path, methodRequired, params);
    return method.getResponseBodyAsString();
}

From source file:com.zimbra.cs.util.WebClientServiceUtil.java

/**
 * send service request to one random ui node, keep trying until succeeds.
 * @param serviceUrl the url that should be matched and handled by ServiceServlet in ZimbraWebClient
 *        reqHeaders the map of req/rsp attributes that need to be set by the UI node
 * @return response from ui node in String
 * @throws ServiceException//  w  w  w  .  ja va 2s .c o m
 */
public static String sendServiceRequestToOneRandomUiNode(String serviceUrl, Map<String, String> reqHeaders)
        throws ServiceException {
    List<Server> servers = Provisioning.getInstance().getAllServers(Provisioning.SERVICE_WEBCLIENT);
    if (servers == null || servers.isEmpty()) {
        servers.add(Provisioning.getInstance().getLocalServer());
    }
    HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
    HttpProxyUtil.configureProxy(client);
    AuthToken authToken = AuthProvider.getAdminAuthToken();
    ZimbraLog.misc.debug("got admin auth token");
    String resp = "";
    for (Server server : servers) {
        if (isServerAtLeast8dot5(server)) {
            HttpMethod method = null;
            try {
                method = new GetMethod(URLUtil.getServiceURL(server, serviceUrl, false));
                ZimbraLog.misc.debug("connecting to ui node %s", server.getName());
                method.addRequestHeader(PARAM_AUTHTOKEN, authToken.getEncoded());
                // Add all the req headers passed to this function as well
                for (Map.Entry<String, String> entry : reqHeaders.entrySet()) {
                    method.addRequestHeader(entry.getKey(), entry.getValue());
                    ZimbraLog.misc.debug("adding request header %s=%s", entry.getKey(), entry.getValue());
                }
                int result = HttpClientUtil.executeMethod(client, method);
                ZimbraLog.misc.debug("resp: %d", result);
                resp = method.getResponseBodyAsString();
                ZimbraLog.misc.debug("got response from ui node: %s", resp);
                break; //try ui nodes one by one until one succeeds.
            } catch (IOException e) {
                ZimbraLog.misc.warn("failed to get response from ui node", e);
            } catch (AuthTokenException e) {
                ZimbraLog.misc.warn("failed to get authToken", e);
            } finally {
                if (method != null) {
                    method.releaseConnection();
                }
            }
        }
    }
    if (authToken != null && authToken.isRegistered()) {
        try {
            authToken.deRegister();
            ZimbraLog.misc.debug("de-registered auth token, isRegistered?%s", authToken.isRegistered());
        } catch (AuthTokenException e) {
            ZimbraLog.misc.warn("failed to de-register authToken", e);
        }
    }
    return resp;
}