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

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

Introduction

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

Prototype

@Override
public String getResponseBodyAsString() throws IOException 

Source Link

Document

Returns the response body of the HTTP method, if any, as a String .

Usage

From source file:org.eclipse.mylyn.internal.jira.core.service.web.JiraWebClient.java

protected void handleErrorMessage(HttpMethodBase method) throws JiraException {
    try {/*  ww  w  .jav a 2s.  c o  m*/
        String response = method.getResponseBodyAsString();
        // TODO consider logging the error

        if (method.getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE) {
            throw new JiraRemoteException("JIRA system error", null); //$NON-NLS-1$
        }

        if (response == null) {
            throw new JiraRemoteMessageException("Error making JIRA request: " + method.getStatusCode(), ""); //$NON-NLS-1$ //$NON-NLS-2$
        }

        StringReader reader = new StringReader(response);
        try {
            StringBuilder msg = new StringBuilder();
            HtmlStreamTokenizer tokenizer = new HtmlStreamTokenizer(reader, null);
            for (Token token = tokenizer.nextToken(); token.getType() != Token.EOF; token = tokenizer
                    .nextToken()) {
                if (token.getType() == Token.TAG) {
                    HtmlTag tag = (HtmlTag) token.getValue();

                    String classValue = tag.getAttribute("class"); //$NON-NLS-1$
                    if (classValue != null) {
                        if (tag.getTagType() == Tag.DIV) {
                            if (classValue.startsWith("infoBox")) { //$NON-NLS-1$
                                throw new JiraRemoteMessageException(getContent(tokenizer, Tag.DIV));
                            } else if (classValue.startsWith("errorArea")) { //$NON-NLS-1$
                                throw new JiraRemoteMessageException(getContent(tokenizer, Tag.DIV));
                            }
                        } else if (tag.getTagType() == Tag.SPAN) {
                            if (classValue.startsWith("errMsg")) { //$NON-NLS-1$
                                msg.append(getContent(tokenizer, Tag.SPAN));
                            }
                        }
                    }
                }
            }
            if (msg.length() == 0) {
                throw new JiraRemoteMessageException(response);
            } else {
                throw new JiraRemoteMessageException(msg.toString());
            }
        } catch (ParseException e) {
            throw new JiraRemoteMessageException("Error parsing JIRA response: " + method.getStatusCode(), ""); //$NON-NLS-1$ //$NON-NLS-2$
        } finally {
            reader.close();
        }
    } catch (IOException e) {
        throw new JiraException(e);
    }
}

From source file:org.eclipse.mylyn.internal.oslc.core.client.AbstractOslcClient.java

protected void handleReturnCode(int code, HttpMethodBase method) throws CoreException {
    try {/*from  w w  w  .  jav a 2s  .c  o  m*/
        if (code == java.net.HttpURLConnection.HTTP_OK) {
            return;// Status.OK_STATUS;
        } else if (code == java.net.HttpURLConnection.HTTP_MOVED_TEMP
                || code == java.net.HttpURLConnection.HTTP_CREATED) {
            // A new resource created...
            return;// Status.OK_STATUS;
        } else if (code == java.net.HttpURLConnection.HTTP_UNAUTHORIZED
                || code == java.net.HttpURLConnection.HTTP_FORBIDDEN) {
            throw new CoreException(new Status(IStatus.ERROR, IOslcCoreConstants.ID_PLUGIN,
                    "Unable to log into server, ensure repository credentials are correct.")); //$NON-NLS-1$
        } else if (code == java.net.HttpURLConnection.HTTP_PRECON_FAILED) {
            // Mid-air collision
            throw new CoreException(
                    new Status(IStatus.ERROR, IOslcCoreConstants.ID_PLUGIN, "Mid-air collision occurred.")); //$NON-NLS-1$
        } else if (code == java.net.HttpURLConnection.HTTP_CONFLICT) {
            throw new CoreException(
                    new Status(IStatus.ERROR, IOslcCoreConstants.ID_PLUGIN, "A conflict occurred.")); //$NON-NLS-1$
        } else {
            throw new CoreException(new Status(IStatus.ERROR, IOslcCoreConstants.ID_PLUGIN,
                    "Unknown error occurred. Http Code: " + code + " Request: " + method.getURI() //$NON-NLS-1$//$NON-NLS-2$
                            + " Response: " //$NON-NLS-1$
                            + method.getResponseBodyAsString()));
        }
    } catch (URIException e) {
        throw new CoreException(new Status(IStatus.ERROR, IOslcCoreConstants.ID_PLUGIN, "Network Error: " //$NON-NLS-1$
                + e.getMessage()));
    } catch (IOException e) {
        throw new CoreException(new Status(IStatus.ERROR, IOslcCoreConstants.ID_PLUGIN, "Network Error: " //$NON-NLS-1$
                + e.getMessage()));
    }
}

From source file:org.eclipse.mylyn.internal.provisional.commons.soap.AxisHttpFault.java

public static AxisHttpFault makeFault(HttpMethodBase method) throws IOException {
    int returnCode = method.getStatusCode();
    String statusMessage = method.getStatusText();
    AxisHttpFault fault = new AxisHttpFault("HTTP", "(" + returnCode + ")" + statusMessage, returnCode); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    fault.extractDetails(method);/*w  w  w.j a  v a 2s.  co m*/
    fault.setFaultDetailString(Messages.getMessage("return01", "" + returnCode, //$NON-NLS-1$ //$NON-NLS-2$
            method.getResponseBodyAsString()));
    fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode));
    return fault;
}

From source file:org.eclipse.swordfish.plugins.resolver.proxy.impl.HttpCilentProxy.java

@Override
public ClientResponse invoke(ClientRequest request) {
    ClientResponse response = new ClientResponseImpl();
    HttpMethodBase method = getMethod(request.getMethod());

    try {/*  ww w.ja v a2 s .  co m*/
        method.setURI(new URI(request.getURI().toString(), true));
        int statusCode = getClient().executeMethod(method);
        response.setStatus(Status.get(statusCode));

        String responseBody = method.getResponseBodyAsString();
        if (request.getEntityType() != null) {
            Reader responseReader = new StringReader(responseBody);
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            try {
                Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
                response.setEntity(JAXB.unmarshal(responseReader, request.getEntityType()));
            } finally {
                Thread.currentThread().setContextClassLoader(cl);
            }
        } else {
            response.setEntity(responseBody);
        }
    } catch (HttpException e) {
        response.setStatus(Status.ERROR);
        response.setEntity(e);
    } catch (IOException e) {
        response.setStatus(Status.ERROR);
        response.setEntity(e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
    return response;
}

From source file:org.elasticsearch.hadoop.rest.RestClient.java

byte[] execute(HttpMethodBase method, boolean checkStatus) {
    try {/*from www . java  2 s .c  o m*/
        int status = client.executeMethod(method);
        if (checkStatus && status >= HttpStatus.SC_MULTI_STATUS) {
            String body;
            try {
                body = method.getResponseBodyAsString();
            } catch (IOException ex) {
                body = "";
            }
            throw new IllegalStateException(String.format("[%s] on [%s] failed; server[%s] returned [%s]",
                    method.getName(), method.getURI(), client.getHostConfiguration().getHostURL(), body));
        }
        return method.getResponseBody();
    } catch (IOException io) {
        String target;
        try {
            target = method.getURI().toString();
        } catch (IOException ex) {
            target = method.getPath();
        }
        throw new IllegalStateException(
                String.format("Cannot get response body for [%s][%s]", method.getName(), target));
    } finally {
        method.releaseConnection();
    }
}

From source file:org.fcrepo.server.security.servletfilters.pubcookie.ConnectPubcookie.java

public final void connect(String urlString, Map requestParameters, Cookie[] requestCookies,
        String truststoreLocation, String truststorePassword) {
    if (logger.isDebugEnabled()) {
        logger.debug("Entered .connect() " + " url==" + urlString + " requestParameters==" + requestParameters
                + " requestCookies==" + requestCookies);
    }/*  w w  w. ja  v a2s  .  c o  m*/
    responseCookies2 = null;
    URL url = null;
    try {
        url = new URL(urlString);
    } catch (MalformedURLException mue) {
        logger.error("Malformed url: " + urlString, mue);
    }

    if (urlString.startsWith("https:") && null != truststoreLocation && !"".equals(truststoreLocation)
            && null != truststorePassword && !"".equals(truststorePassword)) {
        logger.debug("setting " + FilterPubcookie.TRUSTSTORE_LOCATION_KEY + " to " + truststoreLocation);
        System.setProperty(FilterPubcookie.TRUSTSTORE_LOCATION_KEY, truststoreLocation);
        logger.debug("setting " + FilterPubcookie.TRUSTSTORE_PASSWORD_KEY + " to " + truststorePassword);
        System.setProperty(FilterPubcookie.TRUSTSTORE_PASSWORD_KEY, truststorePassword);

        logger.debug("setting " + FilterPubcookie.KEYSTORE_LOCATION_KEY + " to " + truststoreLocation);
        System.setProperty(FilterPubcookie.KEYSTORE_LOCATION_KEY, truststoreLocation);
        logger.debug("setting " + FilterPubcookie.KEYSTORE_PASSWORD_KEY + " to " + truststorePassword);
        System.setProperty(FilterPubcookie.KEYSTORE_PASSWORD_KEY, truststorePassword);

        System.setProperty("javax.net.debug", "ssl,handshake,data,trustmanager");

    } else {
        logger.debug("DIAGNOSTIC urlString==" + urlString);
        logger.debug("didn't set " + FilterPubcookie.TRUSTSTORE_LOCATION_KEY + " to " + truststoreLocation);
        logger.debug("didn't set " + FilterPubcookie.TRUSTSTORE_PASSWORD_KEY + " to " + truststorePassword);
    }

    HttpClient client = new HttpClient();
    logger.debug(".connect() requestCookies==" + requestCookies);
    HttpMethodBase method = setup(client, url, requestParameters, requestCookies);
    int statusCode = 0;
    try {
        client.executeMethod(method);
        statusCode = method.getStatusCode();
    } catch (Exception e) {
        logger.error("failed original connect, url==" + urlString, e);
    }

    logger.debug("status code==" + statusCode);

    if (302 == statusCode) {
        Header redirectHeader = method.getResponseHeader("Location");
        if (redirectHeader != null) {
            String redirectString = redirectHeader.getValue();
            if (redirectString != null) {
                URL redirectURL = null;
                try {
                    redirectURL = new URL(redirectString);
                    method = setup(client, redirectURL, requestParameters, requestCookies);
                } catch (MalformedURLException mue) {
                    logger.error(".connect() malformed redirect url: " + urlString);
                }
                statusCode = 0;
                try {
                    client.executeMethod(method);
                    statusCode = method.getStatusCode();
                    logger.debug(".connect() (on redirect) statusCode==" + statusCode);
                } catch (Exception e) {
                    logger.error(".connect() " + "failed redirect connect");
                }
            }
        }
    }
    if (statusCode == 200) { // this is either the original, non-302, status code or the status code after redirect
        String content = null;
        try {
            content = method.getResponseBodyAsString();
        } catch (IOException e) {
            logger.error("Error getting content", e);
            return;
        }
        if (content == null) {
            logger.error("Content is null");
            return;
        } else {
            Tidy tidy = null;
            try {
                tidy = new Tidy();
            } catch (Throwable t) {
                logger.error("Error creating Tidy instance?!", t);
            }
            byte[] inputBytes = content.getBytes();
            ByteArrayInputStream inputStream = new ByteArrayInputStream(inputBytes);
            responseDocument = tidy.parseDOM(inputStream, null); //use returned root node as only output
        }
        HttpState state = client.getState();
        try {
            responseCookies2 = method.getRequestHeaders();
            if (logger.isDebugEnabled()) {
                for (Header element : responseCookies2) {
                    logger.debug("Header: {}={}", element.getName(), element.getValue());
                }
            }
            responseCookies = state.getCookies();
            logger.debug(this.getClass().getName() + ".connect() responseCookies==" + responseCookies);
        } catch (Throwable t) {
            logger.error(this.getClass().getName() + ".connect() exception==" + t.getMessage());
            if (t.getCause() != null) {
                logger.error(this.getClass().getName() + ".connect() cause==" + t.getCause().getMessage());
            }
        }
        completedFully = true;
        logger.debug(this.getClass().getName() + ".connect() completedFully==" + completedFully);
    }
}

From source file:org.jahia.services.translation.microsoft.MicrosoftTranslationProvider.java

private String getResponseBodyAsStringQuietly(HttpMethodBase method) {
    try {//  ww  w .j av  a 2 s.com
        return method.getResponseBodyAsString();
    } catch (IOException e) {
        if (logger.isDebugEnabled()) {
            logger.warn("Unable to get response body as string", e);
        }
    }
    return null;
}

From source file:org.jboss.ejb3.test.clusteredservice.unit.HttpUtils.java

public static HttpMethodBase accessURL(URL url, String realm, int expectedHttpCode, Header[] hdrs, int type)
        throws Exception {
    HttpClient httpConn = new HttpClient();
    HttpMethodBase request = createMethod(url, type);

    int hdrCount = hdrs != null ? hdrs.length : 0;
    for (int n = 0; n < hdrCount; n++)
        request.addRequestHeader(hdrs[n]);
    try {//from w  ww  .j a  v a2 s  .c o m
        log.debug("Connecting to: " + url);
        String userInfo = url.getUserInfo();

        if (userInfo != null) {
            UsernamePasswordCredentials auth = new UsernamePasswordCredentials(userInfo);
            httpConn.getState().setCredentials(realm, url.getHost(), auth);
        }
        log.debug("RequestURI: " + request.getURI());
        int responseCode = httpConn.executeMethod(request);
        String response = request.getStatusText();
        log.debug("responseCode=" + responseCode + ", response=" + response);
        String content = request.getResponseBodyAsString();
        log.debug(content);
        // Validate that we are seeing the requested response code
        if (responseCode != expectedHttpCode) {
            throw new IOException("Expected reply code:" + expectedHttpCode + ", actual=" + responseCode);
        }
    } catch (IOException e) {
        throw e;
    }
    return request;
}

From source file:org.jboss.jbossts.txbridge.tests.common.AbstractBasicTests.java

protected void execute(String baseURL, boolean expectResponse) throws Exception {

    HttpMethodBase request = null;

    try {/*from   www .j  a v a  2 s  .  co  m*/
        request = HttpUtils.accessURL(new URL(baseURL));
    } catch (ConnectException e) {
        if (expectResponse) {
            throw e;
        }
    }

    if (expectResponse) {
        String response = request.getResponseBodyAsString().trim();
        assertEquals("finished", response);
    }
}

From source file:org.jboss.mod_cluster.Client.java

public int runit() throws Exception {

    PostMethod pm = null;//from  ww  w .  java 2s  .  c om
    GetMethod gm = null;
    HttpMethodBase bm = null;
    long starttime, endtime;
    if (httpClient == null)
        httpClient = new HttpClient();
    if (fd != null) {
        pm = new PostMethod(URL);
        // InputStreamRequestEntity buf = new InputStreamRequestEntity(fd);
        // XXX: Ugly hack to test...
        byte[] buffet = new byte[6144];
        for (int i = 0; i < buffet.length; i++)
            buffet[i] = 'a';
        ByteArrayRequestEntity buf = new ByteArrayRequestEntity(buffet);
        pm.setRequestEntity(buf);
        // pm.setRequestBody(fd);
        pm.setHttp11(true);
        pm.setContentChunked(true);
        // pm.setRequestContentLength(PostMethod.CONTENT_LENGTH_CHUNKED);
        bm = pm;
    } else if (post != null) {
        pm = new PostMethod(URL);
        pm.setRequestEntity(new StringRequestEntity(post, "application/x-www-form-urlencoded", "UTF8"));
        bm = pm;
    } else {
        gm = new GetMethod(URL);
        bm = gm;
    }
    if (user != null) {
        Credentials cred = new UsernamePasswordCredentials(user, pass);
        httpClient.getState().setCredentials(org.apache.commons.httpclient.auth.AuthScope.ANY, cred);
    }

    // System.out.println("Connecting to " + URL);

    Integer connectionTimeout = 40000;
    bm.getParams().setParameter("http.socket.timeout", connectionTimeout);
    bm.getParams().setParameter("http.connection.timeout", connectionTimeout);
    if (VirtualHost != null)
        bm.getParams().setVirtualHost(VirtualHost);
    httpClient.getParams().setParameter("http.socket.timeout", connectionTimeout);
    httpClient.getParams().setParameter("http.connection.timeout", connectionTimeout);
    if (jsessionid != null) {
        // System.out.println("jsessionid: " + jsessionid);
        bm.setRequestHeader("Cookie", "JSESSIONID=" + jsessionid);
    }

    try {
        if (gm == null) {
            pm.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
            starttime = System.currentTimeMillis();
            httpResponseCode = httpClient.executeMethod(pm);
            endtime = System.currentTimeMillis();
        } else {
            gm.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
            starttime = System.currentTimeMillis();
            httpResponseCode = httpClient.executeMethod(gm);
            endtime = System.currentTimeMillis();
        }

        if (httpResponseCode == 200) {
            response = bm.getResponseBodyAsString();
            Cookie[] cookies = httpClient.getState().getCookies();
            // System.out.println( "Cookies: " + cookies);
            if (cookies != null && cookies.length != 0) {
                for (int i = 0; i < cookies.length; i++) {
                    Cookie cookie = cookies[i];
                    // System.out.println( "Cookie: " + cookie.getName() + ", Value: " + cookie.getValue());
                    if (cookie.getName().equals("JSESSIONID")) {
                        if (jsessionid == null) {
                            jsessionid = cookie.getValue();
                            String nodes[] = jsessionid.split("\\.");
                            if (nodes.length == 2)
                                node = nodes[1];
                            System.out.println("cookie first time: " + jsessionid);
                            bm.releaseConnection();
                            return 0; // first time ok.
                        } else {
                            if (jsessionid.compareTo(cookie.getValue()) == 0) {
                                if (logok)
                                    if (bm.getResponseHeader("Date") != null)
                                        System.out.println("cookie ok: "
                                                + bm.getResponseHeader("Date").toString().replace('\r', ' ')
                                                        .replace('\n', ' ')
                                                + " response time: " + (endtime - starttime));
                                    else {
                                        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                                        Date date = new Date();
                                        System.out.println("cookie ok: " + dateFormat.format(date)
                                                + " response time: " + (endtime - starttime));
                                    }
                                bm.releaseConnection();
                                return 0;
                            } else {
                                System.out.println(
                                        "cookie \"second\" time: " + cookie.getValue() + " : " + jsessionid);
                                System.out.println("cookie changed");
                                bm.releaseConnection();
                                if (checkcookie)
                                    return -1;
                                else if (checknode) {
                                    String nodes[] = cookie.getValue().split("\\.");
                                    if (nodes.length != 2) {
                                        System.out.println("Can't find node in cookie");
                                        return -1;
                                    }
                                    if (nodes[1].compareTo(node) == 0) {
                                        return 0;
                                    } else {
                                        System.out.println("node " + nodes[1] + " changed too");
                                        return -1;
                                    }
                                } else
                                    return 0;
                            }
                        }
                    }
                }
            } else {
                // Look in the response to make sure that there is a cookie.
                int len = (int) bm.getResponseContentLength();

                if (jsessionid != null && bm.getResponseBodyAsString(len).indexOf(jsessionid) != -1) {
                    bm.releaseConnection();
                    return 0;
                }
                if (jsessionid == null && !checkcookie) {
                    return 0;
                }
                System.out.println("No cookies");
            }
            Header head = bm.getResponseHeader("getRequestedSessionId");
            if (head != null) {
                HeaderElement[] heade = head.getElements();
                requestedSessionId = heade[0].getValue();
            } else {
                requestedSessionId = null;
            }
        } else {
            System.out.println("response: " + httpResponseCode);
            System.out.println("response: " + bm.getStatusLine());
            response = bm.getResponseBodyAsString();
            System.out.println("response: " + response);
            success = false;
            httpClient = null;
        }
        // System.out.println("response:\n" + bm.getResponseBodyAsString(len)); 
    } catch (HttpException e) {
        e.printStackTrace();
        success = false;
        httpClient = null;
    }
    System.out.println("DONE: " + httpResponseCode);
    bm.releaseConnection();
    return httpResponseCode;
}