0

Currently I am connecting from android to a .net WEB API using HttpClient and I have been able to do a GET and POST to read/write data. However I want to do an Update and a Delete.

I tried to do this using a POST, but it simple creates more records. Here is my code for the POST, how would I change it to do a PUT or DELETE instead?

        HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://mywebsite.net/api/employees/6");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
        nameValuePairs.add(new BasicNameValuePair("firstName", "UpdatedHello"));
        nameValuePairs.add(new BasicNameValuePair("lastName", "World"));
        nameValuePairs.add(new BasicNameValuePair("employee_name", "UpdatedHello World"));
        nameValuePairs.add(new BasicNameValuePair("password", "xxx"));
        nameValuePairs.add(new BasicNameValuePair("isActive", "1"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));


        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
WaterBoy
  • 697
  • 3
  • 13
  • 35

2 Answers2

1

yeah! the document of httpClient http://hc.apache.org/httpclient-3.x/methods.html

ssskip
  • 259
  • 1
  • 6
  • the same question http://stackoverflow.com/questions/1051004/how-to-send-put-delete-http-request-in-httpurlconnection – ssskip Oct 24 '13 at 03:22
0

You have PutMethod and DeleteMethod API for performing PUT and DELETE Http requests. The sample usage as follows as per doc

PUT Request - The put method is very simple, it takes a URL to put to and requires that the body of the request method be set to the data to upload. The body can be set with an input stream or a string.This method is generally disabled on publicly available servers because it is generally undesireable to allow clients to put new files on the server or to replace existing files.

        PutMethod put = new PutMethod("http://jakarta.apache.org");
        put.setRequestBody(new FileInputStream("UploadMe.gif"));
        // execute the method and handle any error responses.
        ...
        // Handle the response.  Note that a successful response may not be
        // 200, but may also be 201 Created, 204 No Content or any of the other
        // 2xx range responses.

DELETE Request - The delete method is used by supplying a URL to delete the resource at and reading the response from the server.This method is also generally disabled on publicly available servers because it is generally undesireable to allow clients to delete files on the server.

        DeleteMethod delete = new DeleteMethod("http://jakarata.apache.org");
        // execute the method and handle any error responses.
        ...
        // Ensure that if there is a response body it is read, then release the
        // connection.
        ...
        delete.releaseConnection();
Keerthivasan
  • 12,760
  • 2
  • 32
  • 53