Example usage for org.apache.http.client.methods HttpDelete HttpDelete

List of usage examples for org.apache.http.client.methods HttpDelete HttpDelete

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpDelete HttpDelete.

Prototype

public HttpDelete(final String uri) 

Source Link

Usage

From source file:com.sugarcrm.candybean.webservices.WS.java

/**
 * Send a DELETE, GET, POST, or PUT http request, intended for multipart data and JSON requests
 *
 * @param op          The type of http request
 * @param uri         The http endpoint//  w ww  .j  a  v  a 2s  . com
 * @param headers     Map of header key value pairs
 * @param body        A recursive map representing a JSON, where Object is one of String|Map<String,Object>
 * @param contentType The intended content type of the body
 * @return Key Value pairs of the response
 * @throws Exception If HTTP request failed
 */
public static Map<String, Object> request(OP op, String uri, Map<String, String> headers,
        Map<String, Object> body, ContentType contentType) throws Exception {
    if (!verifyBody(body)) {
        throw new CandybeanException("Body is not representable as JSON");
    }
    switch (op) {
    case DELETE:
        return handleRequest(new HttpDelete(uri), headers);
    case GET:
        return handleRequest(new HttpGet(uri), headers);
    case POST:
        HttpPost post = new HttpPost(uri);
        addBodyToRequest(post, body, contentType);
        return handleRequest(post, headers);
    case PUT:
        HttpPut put = new HttpPut(uri);
        addBodyToRequest(put, body, contentType);
        return handleRequest(put, headers);
    default:
        /*
         * JLS 13.4.26: Adding or reordering constants in an enum type will not break compatibility with
         * pre-existing binaries.
         * Thus we include a default in the case that a future version of the enum has a case which is not
         * one of the above
         */
        throw new Exception("Unrecognized OP type... Perhaps your binaries are the wrong version?");
    }
}

From source file:org.wso2.dss.integration.test.odata.ODataTestUtils.java

public static int sendDELETE(String endpoint, Map<String, String> headers) throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpDelete httpDelete = new HttpDelete(endpoint);
    for (String headerType : headers.keySet()) {
        httpDelete.setHeader(headerType, headers.get(headerType));
    }/*from w ww.  j a va 2 s  . c  o  m*/
    HttpResponse httpResponse = httpClient.execute(httpDelete);
    return httpResponse.getStatusLine().getStatusCode();
}

From source file:net.fizzl.redditengine.impl.SimpleHttpClient.java

/**
 * Calls HTTP DELETE with the Request-URI. Returns an InputStream of the response entity.
 * //  www  . jav a2  s .  c  o m
 * @param url   HTTP DELETE URL
 * @return      InputStream
 * @throws ClientProtocolException
 * @throws IOException
 * @throws UnexpectedHttpResponseException
 */
public InputStream delete(String url)
        throws ClientProtocolException, IOException, UnexpectedHttpResponseException {
    HttpDelete delete = new HttpDelete(url);
    return execute(delete);
}

From source file:org.fcrepo.indexer.IndexerGroupIT.java

@Test
public void indexerGroupDeleteTest() throws Exception {
    // create and verify dummy object
    final String pid = "test_pid_5";
    doIndexerGroupUpdateTest(pid);//from  w w  w.j  ava2 s.  c o  m

    Thread.sleep(1200); // Let the creation event persist

    // delete dummy object
    final HttpDelete method = new HttpDelete(serverAddress + pid);
    final HttpResponse response = client.execute(method);
    assertEquals(204, response.getStatusLine().getStatusCode());

    // create update message and send to indexer group
    Message deleteMessage = getMessage("purgeObject", pid);
    indexerGroup.onMessage(deleteMessage);

    FilenameFilter filter = prefixFileFilter(pid);
    waitForFiles(2, filter); // wait for message to be processed

    // two files should exist: one empty and one with data
    File[] files = fileSerializerPath.listFiles(filter);

    assertNotNull(files);
    assertEquals(2, files.length);

    Arrays.sort(files); // sort files by filename (i.e., creation time)
    File f1 = files[0];
    File f2 = files[1];
    assertTrue("Filename doesn't match: " + f1.getAbsolutePath(), f1.getName().startsWith(pid));
    assertTrue("File size too small: " + f1.length(), f1.length() > 500);
    assertTrue("Filename doesn't match: " + f2.getAbsolutePath(), f2.getName().startsWith(pid));
    assertTrue("File size should be 0: " + f2.length(), f2.length() == 0);

    final int expectedTriples = 0;
    waitForTriples(expectedTriples, pid);

    // triples should not exist in the triplestore
    assertTrue("Triples should not exist", sparqlIndexer.countTriples(serverAddress + pid) == expectedTriples);
}

From source file:com.sogeti.droidnetworking.NetworkOperation.java

private int prepareRequest() {
    if (urlString == null || httpMethod == null) {
        return -1;
    }//from  w w  w  . j  a  v a 2s  .co m

    switch (httpMethod) {
    case GET:
        request = new HttpGet(urlString);
        break;
    case POST:
        request = new HttpPost(urlString);
        break;
    case PUT:
        request = new HttpPut(urlString);
        break;
    case DELETE:
        request = new HttpDelete(urlString);
        break;
    case HEAD:
        request = new HttpHead(urlString);
        break;
    default:
        break;
    }

    if (httpMethod == HttpMethod.POST || httpMethod == HttpMethod.PUT) {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

        for (String param : params.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(param, params.get(param)));
        }

        try {
            if (httpMethod == HttpMethod.POST) {
                ((HttpPost) request).setEntity(new UrlEncodedFormEntity(nameValuePairs));
            } else {
                ((HttpPut) request).setEntity(new UrlEncodedFormEntity(nameValuePairs));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    if (useGzip) {
        this.headers.put("Accept-Encoding", "gzip");
    }

    for (String header : headers.keySet()) {
        request.addHeader(header, headers.get(header));
    }

    return 0;
}

From source file:io.coala.capability.online.FluentHCOnlineCapability.java

public static HttpUriRequest getRequest(final HttpMethod method, final URI uri) {
    final HttpRequestBase request;
    switch (method) {
    case POST:// ww  w  .  j  a va2 s . c  om
        request = new HttpPost(uri);// Request.Post(uri);
        break;
    case PUT:
        request = new HttpPut(uri);// Request.Put(uri);
        break;
    case DELETE:
        request = new HttpDelete(uri);// Request.Delete(uri);
        break;
    case GET:
        request = new HttpGet(uri);// Request.Get(uri);
        break;
    default:
        throw new IllegalStateException("UNSUPPORTED: " + method);
    }
    request.setProtocolVersion(HttpVersion.HTTP_1_1);
    final RequestConfig.Builder configBuilder = RequestConfig.custom();
    // TODO read (additional) HTTP client settings from external config
    configBuilder.setExpectContinueEnabled(true);
    request.setConfig(configBuilder.build());
    return request;
}

From source file:org.caratarse.auth.services.controller.UserControllerTest.java

@Test
public void deleteNotExistentUser() throws IOException {
    HttpDelete deleteRequest = new HttpDelete(BASE_URL + "/users/a-not-existent-user");
    HttpResponse response = httpClient.execute(deleteRequest);
    assertEquals(500, response.getStatusLine().getStatusCode());
    log.debug(IOUtils.toString(response.getEntity().getContent()));
}

From source file:org.deviceconnect.android.uiapp.fragment.profile.ExtraProfileFragment.java

/**
 * ??.// w w w  . j  a  va2 s  .c o  m
 * @param view ?
 */
protected void onClickSend(final View view) {
    // 
    final CharSequence inter = ((TextView) getView().findViewById(R.id.fragment_extra_interface)).getText();
    // 
    final CharSequence attr = ((TextView) getView().findViewById(R.id.fragment_extra_attribute)).getText();
    // 
    final String accessToken = getAccessToken();
    // 
    final CharSequence query = ((TextView) getView().findViewById(R.id.fragment_extra_query)).getText();

    final URIBuilder builder = new URIBuilder();
    builder.setProfile(mProfile);
    if (inter != null && inter.length() > 0) {
        builder.setInterface(inter.toString());
    }
    if (attr != null && attr.length() > 0) {
        builder.setAttribute(attr.toString());
    }
    builder.addParameter(DConnectMessage.EXTRA_DEVICE_ID, getSmartDevice().getId());
    if (accessToken != null) {
        builder.addParameter(DConnectMessage.EXTRA_ACCESS_TOKEN, accessToken);
    }
    if (query != null) {
        String path = query.toString();
        if (path.length() > 0) {
            String[] keyvalues = path.split("&");
            for (int i = 0; i < keyvalues.length; i++) {
                String[] kv = keyvalues[i].split("=");
                if (kv.length == 1) {
                    builder.addParameter(kv[0], "");
                } else if (kv.length == 2) {
                    builder.addParameter(kv[0], kv[1]);
                }
            }
        }
    }

    HttpRequest request = null;
    try {
        Spinner spinner = (Spinner) getView().findViewById(R.id.spinner);
        String method = (String) spinner.getSelectedItem();
        if (method.equals("GET")) {
            request = new HttpGet(builder.build());
        } else if (method.equals("POST")) {
            request = new HttpPost(builder.build());
        } else if (method.equals("PUT")) {
            request = new HttpPut(builder.build());
        } else if (method.equals("DELETE")) {
            request = new HttpDelete(builder.build());
        }
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                TextView tv = (TextView) getView().findViewById(R.id.fragment_extra_request);
                try {
                    String uri = builder.build().toASCIIString();
                    tv.setText(uri);
                } catch (URISyntaxException e) {
                    tv.setText("");
                }
            }
        });
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

    (new AsyncTask<HttpRequest, Void, DConnectMessage>() {
        public DConnectMessage doInBackground(final HttpRequest... args) {
            if (args == null || args.length <= 0) {
                return new DConnectResponseMessage(DConnectMessage.RESULT_ERROR);
            }

            DConnectMessage message = new DConnectResponseMessage(DConnectMessage.RESULT_ERROR);
            try {
                HttpRequest request = args[0];
                HttpResponse response = getDConnectClient().execute(getDefaultHost(), request);
                message = (new HttpMessageFactory()).newDConnectMessage(response);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return message;
        }

        @Override
        protected void onPostExecute(final DConnectMessage result) {

            if (getActivity().isFinishing()) {
                return;
            }

            if (result == null) {
                return;
            }
            View view = getView();
            if (view != null) {
                TextView tv = (TextView) view.findViewById(R.id.fragment_extra_response);
                tv.setText(result.toString());
            }
        }
    }).execute(request);
}

From source file:nl.nn.adapterframework.extensions.cmis.CmisHttpSender.java

@Override
public HttpRequestBase getMethod(URIBuilder uri, String message, ParameterValueList pvl,
        Map<String, String> headersParamsMap, IPipeLineSession session) throws SenderException {
    HttpRequestBase method = null;/*from w  ww. j a va  2  s .  co m*/

    try {
        if (getMethodType().equals("GET")) {
            method = new HttpGet(uri.build());
        } else if (getMethodType().equals("POST")) {
            HttpPost httpPost = new HttpPost(uri.build());

            // send data
            if (pvl.getParameterValue("writer") != null) {
                Output writer = (Output) pvl.getParameterValue("writer").getValue();
                ByteArrayOutputStream out = new ByteArrayOutputStream();

                Object clientCompression = pvl.getParameterValue(SessionParameter.CLIENT_COMPRESSION);
                if ((clientCompression != null) && Boolean.parseBoolean(clientCompression.toString())) {
                    httpPost.setHeader("Content-Encoding", "gzip");
                    writer.write(new GZIPOutputStream(out, 4096));
                } else {
                    writer.write(out);
                }

                HttpEntity entity = new BufferedHttpEntity(new ByteArrayEntity(out.toByteArray()));
                httpPost.setEntity(entity);
                out.close();

                method = httpPost;
            }
        } else if (getMethodType().equals("PUT")) {
            HttpPut httpPut = new HttpPut(uri.build());

            // send data
            if (pvl.getParameterValue("writer") != null) {
                Output writer = (Output) pvl.getParameterValue("writer").getValue();
                ByteArrayOutputStream out = new ByteArrayOutputStream();

                Object clientCompression = pvl.getParameterValue(SessionParameter.CLIENT_COMPRESSION);
                if ((clientCompression != null) && Boolean.parseBoolean(clientCompression.toString())) {
                    httpPut.setHeader("Content-Encoding", "gzip");
                    writer.write(new GZIPOutputStream(out, 4096));
                } else {
                    writer.write(out);
                }

                HttpEntity entity = new BufferedHttpEntity(new ByteArrayEntity(out.toByteArray()));
                httpPut.setEntity(entity);
                out.close();

                method = httpPut;
            }
        } else if (getMethodType().equals("DELETE")) {
            method = new HttpDelete(uri.build());
        } else {
            throw new MethodNotSupportedException("method [" + getMethodType() + "] not implemented");
        }
    } catch (Exception e) {
        throw new SenderException(e);
    }

    for (Map.Entry<String, String> entry : headers.entrySet()) {
        log.debug("append header [" + entry.getKey() + "] with value [" + entry.getValue() + "]");

        method.addHeader(entry.getKey(), entry.getValue());
    }

    //Cmis creates it's own contentType depending on the method and bindingType
    method.setHeader("Content-Type", getContentType());

    log.debug(getLogPrefix() + "HttpSender constructed " + getMethodType() + "-method [" + method.getURI()
            + "] query [" + method.getURI().getQuery() + "] ");
    return method;
}

From source file:org.kairosdb.plugin.announce.AnnounceService.java

@Override
public void stop() {
    try {//from  www.j a v a2  s .c  o m
        m_executorService.shutdown();
        HttpClient client = new DefaultHttpClient();

        for (String url : m_discoveryUrls) {
            HttpDelete delete = new HttpDelete(url + "/v1/announcement/" + m_nodeId);
            delete.setHeader("User-Agent", m_nodeId.toString());
            HttpResponse response = client.execute(delete);
            logger.info("Announcement repeal status: " + response.getStatusLine().getStatusCode());
        }
    } catch (IOException e) {
        logger.warn("Failed to repeal announcement", e);
    }
}