0

目前我正在使用 HttpClient 从 android 连接到 .net WEB API,并且我已经能够执行 GET 和 POST 来读取/写入数据。但是我想做一个更新和删除。

我尝试使用 POST 来执行此操作,但它很容易创建更多记录。这是我的 POST 代码,如何将其更改为 PUT 或 DELETE?

        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);
4

2 回答 2

1

是的!httpClient 的文档http://hc.apache.org/httpclient-3.x/methods.html

于 2013-10-24T03:21:08.920 回答
0

您拥有用于执行 PUTPutMethodDeleteMethodDELETE Http 请求的 API。根据文档的示例用法如下

PUT 请求- put 方法非常简单,它需要一个 URL 来放置,并且要求将请求方法的主体设置为要上传的数据。可以使用输入流或字符串设置正文。此方法通常在公开可用的服务器上禁用,因为通常不希望允许客户端将新文件放在服务器上或替换现有文件。

        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 请求- 删除方法通过提供 URL 来删除资源并从服务器读取响应来使用。此方法通常在公共可用服务器上也被禁用,因为通常不希望允许客户端删除服务器上的文件。

        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();
于 2013-10-24T03:27:10.663 回答