Example usage for org.apache.commons.httpclient.methods DeleteMethod getResponseBodyAsStream

List of usage examples for org.apache.commons.httpclient.methods DeleteMethod getResponseBodyAsStream

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods DeleteMethod getResponseBodyAsStream.

Prototype

@Override
public InputStream getResponseBodyAsStream() throws IOException 

Source Link

Document

Returns the response body of the HTTP method, if any, as an InputStream .

Usage

From source file:org.apache.wink.itest.exceptionmappers.JAXRSExceptionsMappedProvidersTest.java

/**
 * Tests a method that throws a NullPointerException inside a called method.
 * /*  ww  w . java 2  s .c  o m*/
 * @throws Exception
 */
public void testNullPointerExceptionMappedProvider() throws Exception {
    HttpClient client = new HttpClient();

    DeleteMethod postMethod = new DeleteMethod(getBaseURI() + "/10000");
    client.executeMethod(postMethod);
    assertEquals(451, postMethod.getStatusCode());

    CommentError c = (CommentError) JAXBContext.newInstance(CommentError.class.getPackage().getName())
            .createUnmarshaller().unmarshal(postMethod.getResponseBodyAsStream());
    assertEquals("The comment did not previously exist.", c.getErrorMessage());
}

From source file:org.apache.wink.itest.exceptionmappers.JAXRSExceptionsMappedProvidersTest.java

/**
 * Tests a method that throws an error.//  w w  w  . j ava2 s.  co m
 * 
 * @throws Exception
 */
public void testErrorMappedProvider() throws Exception {
    HttpClient client = new HttpClient();

    DeleteMethod postMethod = new DeleteMethod(getBaseURI() + "/-99999");
    client.executeMethod(postMethod);
    assertEquals(453, postMethod.getStatusCode());

    CommentError c = (CommentError) JAXBContext.newInstance(CommentError.class.getPackage().getName())
            .createUnmarshaller().unmarshal(postMethod.getResponseBodyAsStream());
    assertEquals("Simulated error", c.getErrorMessage());
}

From source file:org.eclipse.osee.framework.core.util.HttpProcessor.java

public static String delete(URL url) throws Exception {
    String response = null;/*  ww w  .j  a  v a  2  s .co  m*/
    int statusCode = -1;
    DeleteMethod method = new DeleteMethod(url.toString());

    InputStream responseInputStream = null;
    try {
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
        statusCode = executeMethod(url, method);
        if (statusCode == HttpStatus.SC_ACCEPTED) {
            responseInputStream = method.getResponseBodyAsStream();
            response = Lib.inputStreamToString(responseInputStream);
        }
    } catch (Exception ex) {
        throw new Exception(String.format("Error deleting resource: [%s] - status code: [%s]", url, statusCode),
                ex);
    } finally {
        Lib.close(responseInputStream);
        method.releaseConnection();
    }
    return response;
}

From source file:org.geosdi.geoplatform.publish.HttpUtilsLocal.java

public static boolean delete(String url, final String user, final String pw) {

    DeleteMethod httpMethod = null;

    try {/*from ww w.j av  a 2s  .co m*/
        HttpClient client = new HttpClient();
        setAuth(client, url, user, pw);
        httpMethod = new DeleteMethod(url);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        int status = client.executeMethod(httpMethod);
        String response = "";
        if (status == HttpStatus.SC_OK) {
            InputStream is = httpMethod.getResponseBodyAsStream();
            response = IOUtils.toString(is);
            if (response.trim().equals("")) { // sometimes gs rest fails
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(
                            "ResponseBody is empty (this may be not an error since we just performed a DELETE call)");
                }
                return true;
            }
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("(" + status + ") " + httpMethod.getStatusText() + " -- " + url);
            }
            return true;
        } else {
            LOGGER.info("(" + status + ") " + httpMethod.getStatusText() + " -- " + url);
            LOGGER.info("Response: '" + response + "'");
        }
    } catch (ConnectException e) {
        LOGGER.info("Couldn't connect to [" + url + "]");
    } catch (IOException e) {
        LOGGER.info("Error talking to [" + url + "]", e);
    } finally {
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }

    return false;
}

From source file:org.panlab.software.fci.uop.UoPGWClient.java

/**
 * It makes a DELETE towards the gateway
 * @author ctranoris//  w  w  w  .  jav a2 s .c  o  m
 * @param resourceInstance sets the name of the resource Instance, e.g.: uop.rubis_db-27
 * @param ptmAlias sets the name of the provider URI, e.g.: uop
 * @param content sets the name of the content; send in utf8
 */
public void DELETEexecute(String resourceInstance, String ptmAlias, String content) {
    System.out.println("content body=" + "\n" + content);
    HttpClient client = new HttpClient();
    String tgwcontent = content;

    // resource instance is like uop.rubis_db-6 so we need to make it like
    // this /uop/uop.rubis_db-6
    String ptm = ptmAlias;
    String url = uopGWAddress + "/" + ptm + "/" + resourceInstance;
    System.out.println("Request: " + url);

    // Create a method instance.

    DeleteMethod delMethod = new DeleteMethod(url);
    delMethod.setRequestHeader("User-Agent", userAgent);
    delMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    // Provide custom retry handler is necessary
    //      delMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
    //            new DefaultHttpMethodRetryHandler(3, false));

    //      RequestEntity requestEntity = null;
    //      try {
    //         requestEntity = new StringRequestEntity(tgwcontent,
    //               "application/x-www-form-urlencoded", "utf-8");
    //      } catch (UnsupportedEncodingException e1) {
    //         e1.printStackTrace();
    //      }

    //delMethod.setRequestEntity(requestEntity);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(delMethod);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + delMethod.getStatusLine());
        }

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary
        // data
        // print the status and response
        InputStream responseBody = delMethod.getResponseBodyAsStream();

        CopyInputStream cis = new CopyInputStream(responseBody);
        response_stream = cis.getCopy();
        System.out.println("Response body=" + "\n" + convertStreamToString(response_stream));
        response_stream.reset();

        //         System.out.println("for address: " + url + " the response is:\n "
        //               + post.getResponseBodyAsString());

    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // Release the connection.
        delMethod.releaseConnection();
    }

}

From source file:org.sonatype.nexus.restlight.common.AbstractRESTLightClient.java

/**
 * <p>//from   w ww  .  j av  a  2  s .  c om
 * Low-level DELETE implementation.
 * </p>
 * <p>
 * Submit a DELETE request to the URL given (absolute or relative-to-base-URL depends on urlIsAbsolute flag), and
 * parse the response as an XML {@link Document} (JDOM) instance <b>if</b> expectResponseBody == true. Use the given
 * requestParams map to inject into the HTTP DELETE method.
 * </p>
 */
protected Document doDelete(final String url, final Map<String, ? extends Object> requestParams,
        final boolean urlIsAbsolute, final boolean expectResponseBody) throws RESTLightClientException {
    DeleteMethod method = urlIsAbsolute ? new DeleteMethod(url) : new DeleteMethod(baseUrl + url);

    addRequestParams(method, requestParams);

    try {
        client.executeMethod(method);
    } catch (HttpException e) {
        throw new RESTLightClientException("DELETE request execution failed. Reason: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new RESTLightClientException("DELETE request execution failed. Reason: " + e.getMessage(), e);
    }

    int status = method.getStatusCode();

    String statusText = method.getStatusText();

    if (status != 200) {
        throw new RESTLightClientException("DELETE request failed; HTTP status: " + status + ": " + statusText);
    }

    if (expectResponseBody) {
        try {
            return new SAXBuilder().build(method.getResponseBodyAsStream());
        } catch (JDOMException e) {
            throw new RESTLightClientException("Failed to parse response body as XML for DELETE request.", e);
        } catch (IOException e) {
            throw new RESTLightClientException("Could not retrieve body as a String from DELETE request.", e);
        } finally {
            method.releaseConnection();
        }
    } else {
        method.releaseConnection();

        return null;
    }
}

From source file:org.sonatype.nexus.restlight.testharness.DELETEFixtureTest.java

@Test
public void testDelete() throws HttpException, IOException, JDOMException {
    Document doc = new Document().setRootElement(new Element("root"));

    fixture.setResponseDocument(doc);//from   ww  w  .  j a  va 2 s .  com

    String url = "http://localhost:" + fixture.getPort();
    HttpClient client = new HttpClient();
    setupAuthentication(client);

    DeleteMethod get = new DeleteMethod(url);

    client.executeMethod(get);

    SAXBuilder builder = new SAXBuilder();
    Document resp = builder.build(get.getResponseBodyAsStream());

    get.releaseConnection();

    XMLOutputter outputter = new XMLOutputter(Format.getCompactFormat());
    assertEquals(outputter.outputString(doc), outputter.outputString(resp));
}