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

PUT および DELETE Http 要求を実行するための APIがPutMethodあります。DeleteMethodドキュメントごとに次のようなサンプル使用法

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 に答える