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.alfresco.repo.transfer.HttpClientTransmitterImpl.java

/**
 *
 *//*from   www  . java  2  s .c  o  m*/
public TransferProgress getStatus(Transfer transfer) throws TransferException {
    TransferTarget target = transfer.getTransferTarget();
    HttpMethod statusRequest = getPostMethod();
    try {
        HostConfiguration hostConfig = getHostConfig(target);
        HttpState httpState = getHttpState(target);

        statusRequest.setPath(target.getEndpointPath() + "/status");
        //Put the transferId on the query string
        statusRequest.setQueryString(
                new NameValuePair[] { new NameValuePair("transferId", transfer.getTransferId()) });

        try {
            int responseStatus = httpClient.executeMethod(hostConfig, statusRequest, httpState);
            checkResponseStatus("status", responseStatus, statusRequest);
            //If we get here then we've received a 200 response
            String statusPayload = statusRequest.getResponseBodyAsString();
            JSONObject statusObj = new JSONObject(statusPayload);
            //We're expecting the transfer progress encoded in a JSON object...
            int currentPosition = statusObj.getInt("currentPosition");
            int endPosition = statusObj.getInt("endPosition");
            String statusStr = statusObj.getString("status");

            TransferProgress p = new TransferProgress();

            if (statusObj.has("error")) {
                JSONObject errorJSON = statusObj.getJSONObject("error");
                Throwable throwable = rehydrateError(errorJSON);
                p.setError(throwable);
            }

            p.setStatus(TransferProgress.Status.valueOf(statusStr));
            p.setCurrentPosition(currentPosition);
            p.setEndPosition(endPosition);

            return p;
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            String error = "Failed to execute HTTP request to target";
            log.debug(error, e);
            throw new TransferException(MSG_HTTP_REQUEST_FAILED,
                    new Object[] { "status", target.toString(), e.toString() }, e);
        }
    } finally {
        statusRequest.releaseConnection();
    }
}

From source file:org.alfresco.wcm.client.impl.WebScriptCallerImpl.java

void discardResponse(HttpMethod httpMethod) throws IOException {
    if (log.isDebugEnabled()) {
        log.debug("Received non-OK response when invoking method on path " + httpMethod.getPath()
                + ". Response was:\n" + httpMethod.getResponseBodyAsString());
    } else {/*from  w  w  w . j ava  2s. c om*/
        byte[] buf = localBuffer.get();
        InputStream responseStream = httpMethod.getResponseBodyAsStream();
        while (responseStream.read(buf) != -1)
            ;
    }
}

From source file:org.alfresco.web.bean.ajax.PresenceProxyBean.java

/**
 * Perform request/*from  ww w  . ja v a  2s .c o  m*/
 */
public String getUrlResponse(String requestUrl) {
    String response = "";
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(requestUrl);
    method.setRequestHeader("Accept", "*/*");
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
    try {
        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            response = method.getResponseBodyAsString();
        } else {
            response = method.getStatusText();
        }
    } catch (HttpException e) {
        response = e.getMessage();
    } catch (IOException e) {
        response = e.getMessage();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return response;
}

From source file:org.apache.camel.component.jetty.HttpHeaderCaseTest.java

@Test
public void testHttpHeaderCase() throws Exception {
    HttpClient client = new HttpClient();
    HttpMethod method = new PostMethod("http://localhost:" + getPort() + "/myapp/mytest");

    method.setRequestHeader("clientHeader", "fooBAR");
    method.setRequestHeader("OTHER", "123");
    method.setRequestHeader("beer", "Carlsberg");

    client.executeMethod(method);/* ww w  .j av  a 2  s.c  om*/

    assertEquals("Bye World", method.getResponseBodyAsString());
    assertEquals("aBc123", method.getResponseHeader("MyCaseHeader").getValue());
    assertEquals("456DEf", method.getResponseHeader("otherCaseHeader").getValue());
}

From source file:org.apache.cloudstack.network.element.SspClient.java

private String executeMethod(HttpMethod method) {
    String apiCallPath = null;//from  w  w w  . ja v a2s.c  o  m
    try {
        apiCallPath = method.getName() + " " + method.getURI().toString();
    } catch (URIException e) {
        s_logger.error("method getURI failed", e);
    }

    String response = null;
    try {
        client.executeMethod(method);
        response = method.getResponseBodyAsString();
    } catch (HttpException e) {
        s_logger.error("ssp api call failed " + apiCallPath, e);
        return null;
    } catch (IOException e) {
        s_logger.error("ssp api call failed " + apiCallPath, e);
        return null;
    } finally {
        method.releaseConnection();
    }

    if (method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
        if (!login()) {
            return null;
        }

        try {
            client.executeMethod(method);
            response = method.getResponseBodyAsString();
        } catch (HttpException e) {
            s_logger.error("ssp api call failed " + apiCallPath, e);
            return null;
        } catch (IOException e) {
            s_logger.error("ssp api call failed " + apiCallPath, e);
            return null;
        } finally {
            method.releaseConnection();
        }
    }
    s_logger.info("ssp api call:" + apiCallPath + " user=" + username + " status=" + method.getStatusLine());
    if (method instanceof EntityEnclosingMethod) {
        EntityEnclosingMethod emethod = (EntityEnclosingMethod) method;
        RequestEntity reqEntity = emethod.getRequestEntity();
        if (reqEntity instanceof StringRequestEntity) {
            StringRequestEntity strReqEntity = (StringRequestEntity) reqEntity;
            s_logger.debug("ssp api request body:" + strReqEntity.getContent());
        } else {
            s_logger.debug("ssp api request body:" + emethod.getRequestEntity());
        }
    }
    s_logger.debug("ssp api response body:" + response);
    return response;
}

From source file:org.apache.cocoon.transformation.SparqlTransformer.java

private void executeRequest(String url, String method, Map httpHeaders, SourceParameters requestParameters)
        throws ProcessingException, IOException, SAXException {
    HttpClient httpclient = new HttpClient();
    if (System.getProperty("http.proxyHost") != null) {
        // getLogger().warn("PROXY: "+System.getProperty("http.proxyHost"));
        String nonProxyHostsRE = System.getProperty("http.nonProxyHosts", "");
        if (nonProxyHostsRE.length() > 0) {
            String[] pHosts = nonProxyHostsRE.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*").split("\\|");
            nonProxyHostsRE = "";
            for (String pHost : pHosts) {
                nonProxyHostsRE += "|(^https?://" + pHost + ".*$)";
            }/*ww w  . java 2 s.  co  m*/
            nonProxyHostsRE = nonProxyHostsRE.substring(1);
        }
        if (nonProxyHostsRE.length() == 0 || !url.matches(nonProxyHostsRE)) {
            try {
                HostConfiguration hostConfiguration = httpclient.getHostConfiguration();
                hostConfiguration.setProxy(System.getProperty("http.proxyHost"),
                        Integer.parseInt(System.getProperty("http.proxyPort", "80")));
                httpclient.setHostConfiguration(hostConfiguration);
            } catch (Exception e) {
                throw new ProcessingException("Cannot set proxy!", e);
            }
        }
    }
    // Make the HttpMethod.
    HttpMethod httpMethod = null;
    // Do not use empty query parameter.
    if (requestParameters.getParameter(parameterName).trim().equals("")) {
        requestParameters.removeParameter(parameterName);
    }
    // Instantiate different HTTP methods.
    if ("GET".equalsIgnoreCase(method)) {
        httpMethod = new GetMethod(url);
        if (requestParameters.getEncodedQueryString() != null) {
            httpMethod.setQueryString(
                    requestParameters.getEncodedQueryString().replace("\"", "%22")); /* Also escape '"' */
        } else {
            httpMethod.setQueryString("");
        }
    } else if ("POST".equalsIgnoreCase(method)) {
        PostMethod httpPostMethod = new PostMethod(url);
        if (httpHeaders.containsKey(HTTP_CONTENT_TYPE) && ((String) httpHeaders.get(HTTP_CONTENT_TYPE))
                .startsWith("application/x-www-form-urlencoded")) {
            // Encode parameters in POST body.
            Iterator parNames = requestParameters.getParameterNames();
            while (parNames.hasNext()) {
                String parName = (String) parNames.next();
                httpPostMethod.addParameter(parName, requestParameters.getParameter(parName));
            }
        } else {
            // Use query parameter as POST body
            httpPostMethod.setRequestBody(requestParameters.getParameter(parameterName));
            // Add other parameters to query string
            requestParameters.removeParameter(parameterName);
            if (requestParameters.getEncodedQueryString() != null) {
                httpPostMethod.setQueryString(
                        requestParameters.getEncodedQueryString().replace("\"", "%22")); /* Also escape '"' */
            } else {
                httpPostMethod.setQueryString("");
            }
        }
        httpMethod = httpPostMethod;
    } else if ("PUT".equalsIgnoreCase(method)) {
        PutMethod httpPutMethod = new PutMethod(url);
        httpPutMethod.setRequestBody(requestParameters.getParameter(parameterName));
        requestParameters.removeParameter(parameterName);
        httpPutMethod.setQueryString(requestParameters.getEncodedQueryString());
        httpMethod = httpPutMethod;
    } else if ("DELETE".equalsIgnoreCase(method)) {
        httpMethod = new DeleteMethod(url);
        httpMethod.setQueryString(requestParameters.getEncodedQueryString());
    } else {
        throw new ProcessingException("Unsupported method: " + method);
    }
    // Authentication (optional).
    if (credentials != null && credentials.length() > 0) {
        String[] unpw = credentials.split("\t");
        httpclient.getParams().setAuthenticationPreemptive(true);
        httpclient.getState().setCredentials(new AuthScope(httpMethod.getURI().getHost(),
                httpMethod.getURI().getPort(), AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(unpw[0], unpw[1]));
    }
    // Add request headers.
    Iterator headers = httpHeaders.entrySet().iterator();
    while (headers.hasNext()) {
        Map.Entry header = (Map.Entry) headers.next();
        httpMethod.addRequestHeader((String) header.getKey(), (String) header.getValue());
    }
    // Declare some variables before the try-block.
    XMLizer xmlizer = null;
    try {
        // Execute the request.
        int responseCode;
        responseCode = httpclient.executeMethod(httpMethod);
        // Handle errors, if any.
        if (responseCode < 200 || responseCode >= 300) {
            if (showErrors) {
                AttributesImpl attrs = new AttributesImpl();
                attrs.addCDATAAttribute("status", "" + responseCode);
                xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "error", "sparql:error", attrs);
                String responseBody = httpMethod.getStatusText(); //httpMethod.getResponseBodyAsString();
                xmlConsumer.characters(responseBody.toCharArray(), 0, responseBody.length());
                xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "error", "sparql:error");
                return; // Not a nice, but quick and dirty way to end.
            } else {
                throw new ProcessingException("Received HTTP status code " + responseCode + " "
                        + httpMethod.getStatusText() + ":\n" + httpMethod.getResponseBodyAsString());
            }
        }
        // Parse the response
        if (responseCode == 204) { // No content.
            String statusLine = httpMethod.getStatusLine().toString();
            xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "result", "sparql:result", EMPTY_ATTRIBUTES);
            xmlConsumer.characters(statusLine.toCharArray(), 0, statusLine.length());
            xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "result", "sparql:result");
        } else if (parse.equalsIgnoreCase("xml")) {
            InputStream responseBodyStream = httpMethod.getResponseBodyAsStream();
            xmlizer = (XMLizer) manager.lookup(XMLizer.ROLE);
            xmlizer.toSAX(responseBodyStream, "text/xml", httpMethod.getURI().toString(),
                    new IncludeXMLConsumer(xmlConsumer));
            responseBodyStream.close();
        } else if (parse.equalsIgnoreCase("text")) {
            xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "result", "sparql:result", EMPTY_ATTRIBUTES);
            String responseBody = httpMethod.getResponseBodyAsString();
            xmlConsumer.characters(responseBody.toCharArray(), 0, responseBody.length());
            xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "result", "sparql:result");
        } else {
            throw new ProcessingException("Unknown parse type: " + parse);
        }
    } catch (ServiceException e) {
        throw new ProcessingException("Cannot find the right XMLizer for " + XMLizer.ROLE, e);
    } finally {
        if (xmlizer != null)
            manager.release((Component) xmlizer);
        httpMethod.releaseConnection();
    }
}

From source file:org.apache.commons.httpclient.demo.MultiThreadedHttpDemo.java

public static void main(String[] args) {
    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    HttpClient client = new HttpClient(connectionManager);
    ///*from w  w w.  ja  v  a  2  s .com*/
    //client.getHostConfiguration().setProxy("90.0.12.21",808);
    //GETHTTPSURLhttphttps
    HttpMethod method = new GetMethod("http://java.sun.com");
    //POST
    //HttpMethod method = new PostMethod("http://java.sun.com");
    try {
        client.executeMethod(method);
    } catch (IOException ex) {
    }
    //
    System.out.println("===================================");
    System.out.println("");
    System.out.println(method.getStatusLine());
    System.out.println("===================================");
    //
    System.out.println("===================================");
    System.out.println(":");
    try {
        System.out.println(method.getResponseBodyAsString());
    } catch (IOException ex1) {
    }
    System.out.println("===================================");
    //
    method.releaseConnection();
}

From source file:org.apache.commons.httpclient.demo.SimpleClient.java

public static void main(String[] args) throws IOException {
    HttpClient client = new HttpClient();
    ///*from w w  w  . j a va2s  .  c o  m*/
    client.getHostConfiguration().setProxy("90.0.12.21", 808);
    //GETHTTPSURLhttphttps
    HttpMethod method = new GetMethod("http://java.sun.com");
    //POST
    //HttpMethod method = new PostMethod("http://java.sun.com");
    client.executeMethod(method);
    //
    System.out.println("===================================");
    System.out.println("");
    System.out.println(method.getStatusLine());
    System.out.println("===================================");
    //
    System.out.println("===================================");
    System.out.println(":");
    System.out.println(method.getResponseBodyAsString());
    System.out.println("===================================");
    //
    method.releaseConnection();
}

From source file:org.apache.commons.httpclient.demo.SimpleHttpClient.java

public static void main(String[] args) throws IOException {

    HttpClient client = new HttpClient();
    ///* w  w  w  . j  a v a2 s.  co m*/
    //client.getHostConfiguration().setProxy("90.0.12.21",808);

    client.getHostConfiguration().setHost("www.imobile.com.cn", 80, "http");
    HttpMethod method = getPostMethod(); //POST
    //HttpMethod method = getPostMethod(); //GET
    client.executeMethod(method);

    //
    System.out.println("===================================");
    System.out.println("");
    System.out.println(method.getStatusLine());
    System.out.println("===================================");

    //
    String response = new String(method.getResponseBodyAsString().getBytes("8859_1"));
    //
    System.out.println("===================================");
    System.out.println(":");
    System.out.println(response);
    System.out.println("===================================");

    method.releaseConnection();
}

From source file:org.apache.cxf.aegis.jaxws.AegisJaxwsGetTest.java

@Test
public void testGetEcho() throws Exception {
    HttpClient httpClient = createClient();
    String url = "http://localhost:" + PORT + "/Echo/echo/echo/hello";
    HttpMethod method = null;
    method = new GetMethod(url);
    int status = httpClient.executeMethod(method);
    assertEquals(HttpStatus.SC_OK, status);
    String result = method.getResponseBodyAsString();
    assertTrue(result.contains("hello"));
    method.releaseConnection();/*w  w  w  .  j  a  va 2  s.co  m*/

    httpClient = createClient();
    url = "http://localhost:" + PORT + "/Echo/echo/echo/hello?wsdl";
    method = new GetMethod(url);
    status = httpClient.executeMethod(method);
    assertEquals(HttpStatus.SC_OK, status);
    Document doc = StaxUtils.read(method.getResponseBodyAsStream());
    Map<String, String> ns = new HashMap<String, String>();
    ns.put("xsd", "http://www.w3.org/2001/XMLSchema");
    NodeList nl = XPathAssert.assertValid("//xsd:element[@name='firstHeader']", doc.getDocumentElement(), ns);
    assertEquals(1, nl.getLength());
}