在Android中发送HTTP DELETE请求

时间:2012-04-26 17:44:15

标签: android httpwebrequest

我的客户端API指定要删除对象,必须发送DELETE请求,其中包含描述内容的Json头数据。实际上它与添加对象的调用相同,这是通过POST完成的。这很好用,我的代码的内容如下:

HttpURLConnection con = (HttpURLConnection)myurl.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setUseCaches(false);
con.connect();
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(data); // data is the post data to send
wr.flush();

要发送删除请求,我将请求方法更改为“DELETE”。但是我收到以下错误:

java.net.ProtocolException: DELETE does not support writing

所以,我的问题是,如何从Android发送包含标题数据的DELETE请求?我错过了这一点 - 您是否能够将标题数据添加到DELETE请求中?感谢。

9 个答案:

答案 0 :(得分:30)

有问题的行是con.setDoOutput(true);。删除它将修复错误。

您可以使用addRequestPropertysetRequestProperty向DELETE添加请求标头,但无法添加请求正文。

答案 1 :(得分:4)

getOutputStream()仅适用于具有正文的请求,例如POST。在没有正文的请求(如DELETE)上使用它将抛出ProtocolException。相反,您应该使用addHeader()添加标头,而不是调用getOutputStream()。

答案 2 :(得分:4)

我知道有点晚了,但是如果有人像我一样在谷歌搜索我这样解决了:

if went_too_far(my_iterator.peek()):
    break
else:
    item = next(my_iterator)

答案 3 :(得分:3)

This is a limitation of HttpURLConnection, on old Android versions (<=4.4).

While you could alternatively use HttpClient, I don't recommend it as it's an old library with several issues that was removed from Android 6.

I would recommend using a new recent library like OkHttp:

OkHttpClient client = new OkHttpClient();
Request.Builder builder = new Request.Builder()
    .url(getYourURL())
    .delete(RequestBody.create(
        MediaType.parse("application/json; charset=utf-8"), getYourJSONBody()));

Request request = builder.build();

try {
    Response response = client.newCall(request).execute();
    String string = response.body().string();
    // TODO use your response
} catch (IOException e) {
    e.printStackTrace();
}

答案 4 :(得分:2)

尝试以下方法调用HttpDelete方法,它对我有用,希望能为你工作

String callHttpDelete(String url){

             try {
                    HttpParams httpParams = new BasicHttpParams();
                    HttpConnectionParams.setConnectionTimeout(httpParams, 15000);
                    HttpConnectionParams.setSoTimeout(httpParams, 15000);

                    //HttpClient httpClient = getNewHttpClient();
                    HttpClient httpClient = new DefaultHttpClient();// httpParams);


                    HttpResponse response = null;    
                    HttpDelete httpDelete = new HttpDelete(url);    
                    response = httpClient.execute(httpDelete); 

                    String sResponse;

                    StringBuilder s = new StringBuilder();

                    while ((sResponse = reader.readLine()) != null) {
                        s = s.append(sResponse);
                    }

                    Log.v(tag, "Yo! Response recvd ["+s.toString()+"]");
                    return s.toString();
                } catch (Exception e){
                    e.printStackTrace();
                }
              return s.toString();
        }

答案 5 :(得分:2)

DELETE请求是GET请求的扩展形式,根据android文档,您无法在DELETE请求的主体中写入。 HttpUrlConnection将抛出“无法编写协议异常”。

如果您仍想在体内编写参数,我建议您使用 OKHttp 库。

OKHttp documentation

如果您有兴趣使用更简单的库,那么您可以尝试 SimpleHttpAndroid library

要记住的一件事是,如果你没有在身体上写任何东西,那么删除行

conn.setDoOutput(true);

谢谢,希望它可能会有所帮助。

答案 6 :(得分:0)

您不能只使用addHeader()方法吗?

答案 7 :(得分:0)

这是我的Delete请求方法。

只需post请求额外RequestProperty

connection.setRequestProperty("X-HTTP-Method-Override", "DELETE");

完整方法下方。

    public void executeDeleteRequest(String stringUrl, JSONObject jsonObject, String reqContentType, String resContentType, int timeout) throws Exception {
    URL url = new URL(stringUrl);
    HttpURLConnection connection = null;
    String urlParameters = jsonObject.toString();
    try {
        connection = (HttpURLConnection) url.openConnection();

        //Setting the request properties and header
        connection.setRequestProperty("X-HTTP-Method-Override", "DELETE");
        connection.setRequestMethod("POST");
        connection.setRequestProperty("User-Agent", USER_AGENT);
        connection.setRequestProperty(CONTENT_TYPE_KEY, reqContentType);
        connection.setRequestProperty(ACCEPT_KEY, resContentType);


        connection.setReadTimeout(timeout);
        connection.setConnectTimeout(defaultTimeOut);

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        // Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
        responseCode = connection.getResponseCode();
        // To handle web services which server responds with response code
        // only
        try {
            response = convertStreamToString(connection.getInputStream());
        } catch (Exception e) {
            Log.e(Log.TAG_REST_CLIENT, "Cannot convert the input stream to string for the url= " + stringUrl + ", Code response=" + responseCode + "for the JsonObject: " + jsonObject.toString(), context);
        }
    } catch (
            Exception e
            )

    {
        if (!BController.isInternetAvailable(context)) {
            IntentSender.getInstance().sendIntent(context, Constants.BC_NO_INTERNET_CONNECTION);
            Log.e(Log.TAG_REST_CLIENT, "No internet connection", context);
        }
        Log.e(Log.TAG_REST_CLIENT, "Cannot perform the POST request successfully for the following URL: " + stringUrl + ", Code response=" + responseCode + "for the JsonObject: " + jsonObject.toString(), context);
        throw e;
    } finally{

        if (connection != null) {
            connection.disconnect();
        }
    }

}

我希望它有所帮助。

答案 8 :(得分:-7)

要为此问题添加闭包,发现没有受支持的方法来发送包含标头数据的HTTP DELETE请求。

解决方案是让客户端更改其API以接受标准GET请求,该请求表明该操作应该是删除操作,包含要删除的项目的ID。

http://clienturl.net/api/delete/id12345