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:org.xmlsh.internal.commands.http.java

@Override
public int run(List<XValue> args) throws Exception {

    Options opts = new Options(
            "retry:,get:,put:,post:,head:,options:,delete:,connectTimeout:,contentType:,readTimeout:,+useCaches,+followRedirects,user:,password:,H=add-header:+,disableTrust:,keystore:,keypass:,sslproto:,output-headers=ohead:");
    opts.parse(args);/* w  w  w . j a v a2s.c o  m*/

    setSerializeOpts(getSerializeOpts(opts));

    HttpRequestBase method;

    String surl = null;

    if (opts.hasOpt("get")) {
        surl = opts.getOptString("get", null);
        method = new HttpGet(surl);
    } else if (opts.hasOpt("put")) {
        surl = opts.getOptString("put", null);
        method = new HttpPut(surl);
        ((HttpPut) method).setEntity(getInputEntity(opts));
    } else if (opts.hasOpt("post")) {
        surl = opts.getOptString("post", null);
        method = new HttpPost(surl);
        ((HttpPost) method).setEntity(getInputEntity(opts));

    } else if (opts.hasOpt("head")) {
        surl = opts.getOptString("head", null);
        method = new HttpHead(surl);
    } else if (opts.hasOpt("options")) {
        surl = opts.getOptString("options", null);
        method = new HttpOptions(surl);
    } else if (opts.hasOpt("delete")) {
        surl = opts.getOptString("delete", null);
        method = new HttpDelete(surl);
    } else if (opts.hasOpt("trace")) {
        surl = opts.getOptString("trace", null);
        method = new HttpTrace(surl);
    } else {
        surl = opts.getRemainingArgs().get(0).toString();
        method = new HttpGet(surl);
    }

    if (surl == null) {
        usage();
        return 1;
    }

    int ret = 0;

    HttpHost host = new HttpHost(surl);

    DefaultHttpClient client = new DefaultHttpClient();

    setOptions(client, host, opts);

    List<XValue> headers = opts.getOptValues("H");
    if (headers != null) {
        for (XValue v : headers) {
            StringPair pair = new StringPair(v.toString(), '=');
            method.addHeader(pair.getLeft(), pair.getRight());
        }

    }

    int retry = opts.getOptInt("retry", 0);
    long delay = 1000;

    HttpResponse resp = null;

    do {
        try {
            resp = client.execute(method);
            break;
        } catch (IOException e) {
            mShell.printErr("Exception running http" + ((retry > 0) ? " retrying ... " : ""), e);
            if (retry > 0) {
                Thread.sleep(delay);
                delay *= 2;
            } else
                throw e;
        }
    } while (retry-- > 0);

    HttpEntity respEntity = resp.getEntity();
    if (respEntity != null) {
        InputStream ins = respEntity.getContent();
        if (ins != null) {
            try {
                Util.copyStream(ins, getStdout().asOutputStream(getSerializeOpts()));
            } finally {
                ins.close();
            }
        }
    }

    ret = resp.getStatusLine().getStatusCode();
    if (opts.hasOpt("output-headers"))
        writeHeaders(opts.getOptStringRequired("output-headers"), resp.getStatusLine(), resp.getAllHeaders());

    return ret;
}

From source file:com.twotoasters.android.hoot.HootTransportHttpClient.java

@Override
public HootResult synchronousExecute(HootRequest request) {

    HttpRequestBase requestBase = null;//from  ww  w .  j av  a 2 s .co  m
    HootResult result = request.getResult();
    try {
        String uri = request.buildUri().toString();
        switch (request.getOperation()) {
        case DELETE:
            requestBase = new HttpDelete(uri);
            break;
        case GET:
            requestBase = new HttpGet(uri);
            break;
        case PUT:
            HttpPut put = new HttpPut(uri);
            put.setEntity(getEntity(request));
            requestBase = put;
            break;
        case POST:
            HttpPost post = new HttpPost(uri);
            post.setEntity(getEntity(request));
            requestBase = post;
            break;
        case HEAD:
            requestBase = new HttpHead(uri);
            break;
        }
    } catch (UnsupportedEncodingException e1) {
        result.setException(e1);
        e1.printStackTrace();
        return result;
    } catch (IOException e) {
        result.setException(e);
        e.printStackTrace();
        return result;
    }

    synchronized (mRequestBaseMap) {
        mRequestBaseMap.put(request, requestBase);
    }
    if (request.getHeaders() != null && request.getHeaders().size() > 0) {
        for (Object propertyKey : request.getHeaders().keySet()) {
            requestBase.addHeader((String) propertyKey, (String) request.getHeaders().get(propertyKey));
        }
    }

    InputStream is = null;
    try {
        Log.v(TAG, "URI: [" + requestBase.getURI().toString() + "]");
        HttpResponse response = mClient.execute(requestBase);

        if (response != null) {
            result.setResponseCode(response.getStatusLine().getStatusCode());
            Map<String, List<String>> headers = new HashMap<String, List<String>>();
            for (Header header : response.getAllHeaders()) {
                List<String> values = new ArrayList<String>();
                values.add(header.getValue());
                headers.put(header.getName(), values);
            }
            result.setHeaders(headers);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                is = entity.getContent();
                result.setResponseStream(new BufferedInputStream(is));
                request.deserializeResult();
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        result.setException(e);
    } finally {
        requestBase = null;
        synchronized (mRequestBaseMap) {
            mRequestBaseMap.remove(request);
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return result;
}

From source file:org.apache.jena.fuseki.http.DatasetGraphAccessorHTTP.java

private boolean doDelete(String url) {
    try {/*from w  ww .  j a v  a 2  s.co  m*/
        HttpUriRequest httpDelete = new HttpDelete(url);
        exec(url, null, httpDelete, false);
        return true;
    } catch (FusekiNotFoundException ex) {
        return false;
    }
}

From source file:com.sayar.requests.impl.HttpClientRequestHandler.java

public Response execute(final RequestArguments args) throws AuthenticationException, InvalidParameterException {
    // Parse params
    final String url = args.getUrl();
    final Map<String, String> params = args.getParams();
    final HttpAuthentication httpAuth = args.getHttpAuth();

    String formattedUrl;/* w w w . j a v  a 2  s  . co m*/
    try {
        formattedUrl = RequestHandlerUtils.formatUrl(url, params);
    } catch (final UnsupportedEncodingException e) {
        Log.e(RequestsConstants.LOG_TAG, "Unsupported Encoding Exception in Url Parameters.", e);
        throw new InvalidParameterException("Url Parameter Encoding is invalid.");

    }

    final RequestMethod method = args.getMethod();
    HttpUriRequest request = null;
    if (method == RequestMethod.GET) {
        request = new HttpGet(formattedUrl);
    } else if (method == RequestMethod.DELETE) {
        request = new HttpDelete(formattedUrl);
    } else if (method == RequestMethod.OPTIONS) {
        request = new HttpOptions(formattedUrl);
    } else if (method == RequestMethod.HEAD) {
        request = new HttpHead(formattedUrl);
    } else if (method == RequestMethod.TRACE) {
        request = new HttpTrace(formattedUrl);
    } else if (method == RequestMethod.POST || method == RequestMethod.PUT) {
        request = method == RequestMethod.POST ? new HttpPost(formattedUrl) : new HttpPut(formattedUrl);
        if (args.getRequestEntity() != null) {
            ((HttpEntityEnclosingRequestBase) request).setEntity(args.getRequestEntity());
        }
    } else {
        throw new InvalidParameterException("Request Method is not set.");
    }

    if (httpAuth != null) {
        try {
            HttpClientRequestHandler.addAuthentication(request, httpAuth);
        } catch (final AuthenticationException e) {
            Log.e(RequestsConstants.LOG_TAG, "Adding Authentication Failed.", e);
            throw e;
        }
    }
    if (args.getHeaders() != null) {
        HttpClientRequestHandler.addHeaderParams(request, args.getHeaders());
    }

    final Response response = new Response();

    final HttpClient client = this.getHttpClient(args);

    try {
        final HttpResponse httpResponse = client.execute(request);

        response.setResponseVersion(httpResponse.getProtocolVersion());
        response.setStatusAndCode(httpResponse.getStatusLine());

        final HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {
            // Convert the stream into a string and store into the RAW
            // field.
            // InputStream instream = entity.getContent();
            // response.setRaw(RequestHandlerUtils.convertStreamToString(instream));
            // instream.close(); // Closing the input stream will trigger
            // connection release

            // TODO: Perhaps we should be dealing with the charset
            response.setRaw(EntityUtils.toString(entity));

            try {
                // Get the Content Type
                final String contenttype = entity.getContentType().getValue();

                RequestParser parser = null;

                // Check if a request-specific parser was set.
                if (args.getRequestParser() == null) {
                    // Parse the request according to the user's wishes.
                    final String extractionFormat = args.getParseAs();

                    // Determine extraction format if none are set.
                    if (extractionFormat == null) {
                        // If we can not find an appropriate parser, the
                        // default one will be returned.
                        parser = RequestParserFactory.findRequestParser(contenttype);
                    } else {
                        // Try to get the requested parser. This will throw
                        // an exception if we can't get it.
                        parser = RequestParserFactory.getRequestParser(extractionFormat);
                    }
                } else {
                    // Set a request specific parser.
                    parser = args.getRequestParser();
                }

                // Parse the content.. and if it throws an exception log it.
                final Object result = parser.parse(response.getRaw());
                // Check the result of the parser.
                if (result != null) {
                    response.setContent(result);
                    response.setParsedAs(parser.getName());
                } else {
                    // If the parser returned nothing (and most likely it
                    // wasn't the default parser).

                    // We already have the raw response, user the default
                    // parser fallback.
                    response.setContent(RequestParserFactory.DEFAULT_PARSER.parse(response.getRaw()));
                    response.setParsedAs(RequestParserFactory.DEFAULT_PARSER.getName());
                }
            } catch (final InvalidParameterException e) {
                Log.e(RequestsConstants.LOG_TAG, "Parser Requested Could Not Be Found.", e);
                throw e;
            } catch (final Exception e) {
                // Catch any parsing exception.
                Log.e(RequestsConstants.LOG_TAG, "Parser Failed Exception.", e);
                // Informed it was parsed as nothing... aka look at the raw
                // string.
                response.setParsedAs(null);
            }

        } else {
            if (args.getMethod() != RequestMethod.HEAD) {
                Log.w(RequestsConstants.LOG_TAG, "Entity is empty?");
            }
        }
    } catch (final ClientProtocolException e) {
        Log.e(RequestsConstants.LOG_TAG, "Client Protocol Exception", e);
    } catch (final IOException e) {
        Log.e(RequestsConstants.LOG_TAG, "IO Exception.", e);
    } finally {
    }

    return response;
}

From source file:com.iflytek.android.framework.volley.toolbox.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *///from  www . ja v a2  s . co m
@SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST: {
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(request.getUrl());
        }
    }
    case Method.GET:
        return new HttpGet(request.getUrl());
    case Method.DELETE:
        return new HttpDelete(request.getUrl());
    case Method.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        VolleyLog.d("1:" + request.getBodyContentType());
        postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    case Method.HEAD:
        return new HttpHead(request.getUrl());
    case Method.OPTIONS:
        return new HttpOptions(request.getUrl());
    case Method.TRACE:
        return new HttpTrace(request.getUrl());
    case Method.PATCH: {
        HttpPatch patchRequest = new HttpPatch(request.getUrl());
        patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(patchRequest, request);
        return patchRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:azureml_besapp.AzureML_BESApp.java

/**
 * Call REST API for canceling the batch job 
 * /*w  ww .j a v a2s. co  m*/
 * @param job job to be started 
 * @return response from the REST API
 */
public static String besCancelJob(String job) {
    //job_id/start?api-version=2.0
    HttpDelete post;
    HttpClient client;
    StringEntity entity;

    try {
        // create HttpPost and HttpClient object
        post = new HttpDelete(startJobUrl + job);
        client = HttpClientBuilder.create().build();

        // add HTTP headers
        post.setHeader("Accept", "text/json");
        post.setHeader("Accept-Charset", "UTF-8");

        // set Authorization header based on the API key
        post.setHeader("Authorization", ("Bearer " + apikey));

        // Call REST API and retrieve response content
        HttpResponse authResponse = client.execute(post);

        if (authResponse.getEntity() == null) {
            return authResponse.getStatusLine().toString();
        }
        return EntityUtils.toString(authResponse.getEntity());

    } catch (Exception e) {

        return e.toString();
    }
}

From source file:com.hoccer.api.RESTfulApiTest.java

@Test
public void testSigningOffNonexistingClient() throws Exception {

    String uri = ClientConfig.getLinccerBaseUri() + "/clients/" + UUID.randomUUID().toString() + "/environment";

    HttpDelete request = new HttpDelete(uri);
    HttpResponse response = mHttpClient.execute(request);
    assertEquals("should be able to sign off noexisting client uri", 200,
            response.getStatusLine().getStatusCode());
}

From source file:com.floragunn.searchguard.test.helper.rest.RestHelper.java

public HttpResponse executeDeleteRequest(final String request, Header... header) throws Exception {
    return executeRequest(new HttpDelete(getHttpServerUri() + "/" + request), header);
}

From source file:com.palominolabs.crm.sf.rest.HttpApiClient.java

void delete(String sObjectType, Id id) throws IOException {
    executeRequestForString(new HttpDelete(getUri("/sobjects/" + sObjectType + "/" + id)));
}

From source file:com.meltmedia.cadmium.cli.AuthCommand.java

@Override
public void execute() throws Exception {
    if (args == null || args.size() != 2) {
        System.err.println("Please specify action (list|add|remove) and site.");
        System.exit(1);/*from   ww w.j a  v  a 2  s .c  o m*/
    }
    String action = args.get(0);
    String site = this.getSecureBaseUrl(args.get(1) + SERVICE_PATH);
    HttpUriRequest request = null;
    int expectedStatus = HttpStatus.SC_OK;
    if (action.equalsIgnoreCase("list")) {
        System.out.println("Listing site (" + args.get(1) + ") specific users.");
        request = new HttpGet(site);
    } else if (action.equalsIgnoreCase("add")) {
        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
            expectedStatus = HttpStatus.SC_CREATED;
            String passwordHash = hashPasswordForShiro();
            System.out.println("Adding User [" + username + "] with password hash [" + passwordHash + "]");
            request = new HttpPut(site + "/" + username);
            ((HttpPut) request).setEntity(new StringEntity(passwordHash));
        } else {
            System.err.println("Both username and password are required to add a user.");
            System.exit(1);
        }
    } else if (action.equalsIgnoreCase("remove")) {
        if (StringUtils.isNotBlank(username)) {
            expectedStatus = HttpStatus.SC_GONE;
            System.out.println("Removing User [" + username + "]");
            request = new HttpDelete(site + "/" + username);
        } else {
            System.err.println("The username of the user to remove is required.");
            System.exit(1);
        }
    }
    sendRequest(request, expectedStatus);
}