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:com.eucalyptus.blockstorage.CreateSnapshotTest.java

@Test
public void testGetSnapshotInfo() throws Exception {
    HttpClient httpClient = new HttpClient();
    String addr = System.getProperty("euca.objectstorage.url")
            + "/snapset-FuXLn1MUHJ66BkK0/snap-zVl2kZJmjhxnEg..";

    HttpMethodBase method = new GetMethod(addr);
    method.setRequestHeader("Authorization", "Euca");
    method.setRequestHeader("Date", (new Date()).toString());
    method.setRequestHeader("Expect", "100-continue");
    method.setRequestHeader("EucaOperation", "GetSnapshotInfo");
    httpClient.executeMethod(method);/*from ww w.  ja  v  a  2  s . c  o  m*/
    String responseString = method.getResponseBodyAsString();
    System.out.println(responseString);
    method.releaseConnection();
}

From source file:com.eucalyptus.blockstorage.tests.CreateSnapshotTest.java

@Test
public void testGetSnapshotInfo() throws Exception {
    HttpClient httpClient = new HttpClient();
    String addr = System.getProperty(WalrusProperties.URL_PROPERTY)
            + "/snapset-FuXLn1MUHJ66BkK0/snap-zVl2kZJmjhxnEg..";

    HttpMethodBase method = new GetMethod(addr);
    method.setRequestHeader("Authorization", "Euca");
    method.setRequestHeader("Date", (new Date()).toString());
    method.setRequestHeader("Expect", "100-continue");
    method.setRequestHeader("EucaOperation", "GetSnapshotInfo");
    httpClient.executeMethod(method);/* ww  w.ja v  a2  s .  c  om*/
    String responseString = method.getResponseBodyAsString();
    System.out.println(responseString);
    method.releaseConnection();
}

From source file:de.juwimm.cms.common.http.HttpClientWrapper.java

public synchronized String getString(URL destUrl, String userName, String password) throws IOException {
    HttpMethodBase method = invoke(destUrl, userName, password);
    String charSet = method.getRequestCharSet();
    String retString = new String(method.getResponseBodyAsString().getBytes(charSet));
    method.releaseConnection();//from   ww  w .  j  a  v  a2  s.c  o m
    return retString;
}

From source file:com.clarkparsia.sbol.editor.sparql.StardogEndpoint.java

protected void execute(HttpMethodBase post) throws HttpException, IOException, QueryEvaluationException {
    post.setDoAuthentication(true);/*  w w  w .  j a  va  2  s.  com*/

    boolean completed = false;
    try {
        int resultCode = client.executeMethod(post);
        if (resultCode >= 400) {
            throw new HttpException("Code: " + resultCode + " " + post.getResponseBodyAsString());
        }
        completed = true;
    } finally {
        if (!completed) {
            post.abort();
        }
    }
}

From source file:com.arjuna.qa.junit.TestAll.java

private void testCallServlet(String serverUrl, String outfile) {
    boolean result = true;
    try {//w w w  .  j av a  2 s .  c  o m
        // run tests by calling a servlet
        Header runParam = new Header("run", "run");
        HttpMethodBase request = HttpUtils.accessURL(new URL(serverUrl), null, HttpURLConnection.HTTP_OK,
                new Header[] { runParam }, HttpUtils.POST);

        String response = null;
        int index = 0;
        do {
            System.err.println("_____________ " + (index++) + "th round");
            // we have to give some time to the tests to finish
            Thread.sleep(timeout);

            // tries to get results
            request = HttpUtils.accessURL(new URL(serverUrl), null, HttpURLConnection.HTTP_OK, HttpUtils.GET);

            response = request.getResponseBodyAsString();
        } while (response != null && response.indexOf("finished") == -1 && index < LOOP_RETRY_MAX);

        if (response != null && response.indexOf("finished") == -1) {
            System.err.println("======================================================");
            System.err.println("====================  TIMED OUT  =====================");
            System.err.println("======================================================");
            result = false;
        } else {
            System.err.println("======================================================");
            System.err.println("====================   RESULT    =====================");
            System.err.println("======================================================");
            System.err.println(response);
            // writes response to the outfile
            BufferedWriter writer = new BufferedWriter(new FileWriter(outfile));
            writer.write(response);
            writer.close();
        }
    } catch (Exception e) {
        System.err.println("======================================================");
        System.err.println("====================  EXCEPTION  =====================");
        System.err.println("======================================================");
        e.printStackTrace();
        result = false;
    }
    assertTrue(result);
}

From source file:com.linkedin.pinot.server.realtime.ServerSegmentCompletionProtocolHandler.java

private SegmentCompletionProtocol.Response doHttp(SegmentCompletionProtocol.Request request, Part[] parts) {
    SegmentCompletionProtocol.Response response = new SegmentCompletionProtocol.Response(
            SegmentCompletionProtocol.ControllerResponseStatus.NOT_SENT, -1L);
    HttpClient httpClient = new HttpClient();
    ControllerLeaderLocator leaderLocator = ControllerLeaderLocator.getInstance();
    final String leaderAddress = leaderLocator.getControllerLeader();
    if (leaderAddress == null) {
        LOGGER.error("No leader found {}", this.toString());
        return new SegmentCompletionProtocol.Response(
                SegmentCompletionProtocol.ControllerResponseStatus.NOT_LEADER, -1L);
    }// w  w w.  j a va 2  s .  c om
    final String url = request.getUrl(leaderAddress);
    HttpMethodBase method;
    if (parts != null) {
        PostMethod postMethod = new PostMethod(url);
        postMethod.setRequestEntity(new MultipartRequestEntity(parts, new HttpMethodParams()));
        method = postMethod;
    } else {
        method = new GetMethod(url);
    }
    LOGGER.info("Sending request {} for {}", url, this.toString());
    try {
        int responseCode = httpClient.executeMethod(method);
        if (responseCode >= 300) {
            LOGGER.error("Bad controller response code {} for {}", responseCode, this.toString());
            return response;
        } else {
            response = new SegmentCompletionProtocol.Response(method.getResponseBodyAsString());
            LOGGER.info("Controller response {} for {}", response.toJsonString(), this.toString());
            if (response.getStatus().equals(SegmentCompletionProtocol.ControllerResponseStatus.NOT_LEADER)) {
                leaderLocator.refreshControllerLeader();
            }
            return response;
        }
    } catch (IOException e) {
        LOGGER.error("IOException {}", this.toString(), e);
        leaderLocator.refreshControllerLeader();
        return response;
    }
}

From source file:JiraWebClient.java

protected void handleErrorMessage(HttpMethodBase method) throws JiraException {
    try {/*from w  w w. jav a 2 s.c  om*/
        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") || classValue.startsWith("errorArea") //$NON-NLS-1$ //$NON-NLS-2$
                                    || classValue.contains("error")) { //$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:com.cubeia.backoffice.wallet.client.WalletServiceClientHTTP.java

private void assertResponseCodeOK(HttpMethodBase method, int statusCode) throws HttpException {
    if (statusCode != HttpStatus.SC_OK) {
        if (log.isTraceEnabled()) {
            try {
                log.debug("Method call ended in " + statusCode + "; response page: "
                        + method.getResponseBodyAsString());
            } catch (IOException e) {
                log.error("failed to read body", e);
            }/*from w  w w  .java 2 s  .  c o m*/
        }
        throw new HttpException("Method failed: " + method.getStatusLine());
    }
}

From source file:net.praqma.jenkins.rqm.request.RQMHttpClient.java

public int logout() {
    log.finest("Logout");
    try {/*  w ww  .j  a  v  a  2 s .co  m*/
        log.finest("URI:" + url.toURI().toString());
    } catch (URISyntaxException ex) {
        log.finest("Logout URISyntaxException " + ex.getMessage());
    }

    String logoutUrl = this.url.toString() + contextRoot + JAZZ_LOGOUT_URL;
    log.finest("Attempting to log out with this url: " + logoutUrl);
    HttpMethodBase authenticationMethod = new PostMethod(this.url.toString() + contextRoot + JAZZ_LOGOUT_URL);
    authenticationMethod.setFollowRedirects(false);
    UsernamePasswordCredentials credentials = (UsernamePasswordCredentials) super.getState()
            .getCredentials(new AuthScope(host, port));
    if (null != credentials && !(credentials.getUserName().isEmpty() && credentials.getPassword().isEmpty())) {

        log.finest(String.format("Adding authorizationheadder for logout for user: %s",
                credentials.getUserName()));
        authenticationMethod.addRequestHeader("Authorization:",
                "Base " + credentials.getUserName() + ":" + credentials.getPassword());
    }
    String body = "";
    String status = "";
    int responseCode = 0;
    ;
    try {
        responseCode = executeMethod(authenticationMethod);
        body = authenticationMethod.getResponseBodyAsString();
        status = authenticationMethod.getStatusText();
        log.finest(String.format("Response code %s, Status text %s", responseCode, status));
    } catch (Exception e) {
        log.log(Level.SEVERE, "Failed to log out!", e);
        log.log(Level.SEVERE, body);
    }
    return responseCode;
}

From source file:net.sf.antcontrib.net.httpclient.AbstractMethodTask.java

public void execute() throws BuildException {
    if (httpClient == null) {
        httpClient = new HttpClient();
    }/*from   ww w  . jav  a2s  .c  o  m*/

    HttpMethodBase method = createMethodIfNecessary();
    configureMethod(method);
    try {
        int statusCode = httpClient.executeMethod(method);
        if (statusCodeProperty != null) {
            Property p = (Property) getProject().createTask("property");
            p.setName(statusCodeProperty);
            p.setValue(String.valueOf(statusCode));
            p.perform();
        }

        Iterator it = responseHeaders.iterator();
        while (it.hasNext()) {
            ResponseHeader header = (ResponseHeader) it.next();
            Property p = (Property) getProject().createTask("property");
            p.setName(header.getProperty());
            Header h = method.getResponseHeader(header.getName());
            if (h != null && h.getValue() != null) {
                p.setValue(h.getValue());
                p.perform();
            }

        }
        if (responseDataProperty != null) {
            Property p = (Property) getProject().createTask("property");
            p.setName(responseDataProperty);
            p.setValue(method.getResponseBodyAsString());
            p.perform();
        } else if (responseDataFile != null) {
            FileOutputStream fos = null;
            InputStream is = null;
            try {
                is = method.getResponseBodyAsStream();
                fos = new FileOutputStream(responseDataFile);
                byte buf[] = new byte[10 * 1024];
                int read = 0;
                while ((read = is.read(buf, 0, 10 * 1024)) != -1) {
                    fos.write(buf, 0, read);
                }
            } finally {
                FileUtils.close(fos);
                FileUtils.close(is);
            }
        }
    } catch (IOException e) {
        throw new BuildException(e);
    } finally {
        cleanupResources(method);
    }
}