Sending HTTP DELETE request in Android
我的客户端API指定要删除对象,必须发送DELETE请求,其中包含描述内容的Json头数据。 实际上它与添加对象的调用相同,这是通过POST完成的。 这很好用,我的代码的内容如下:
1 2 3 4 5 6 7 8 | 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"。 但是我收到以下错误:
1 | java.net.ProtocolException: DELETE does not support writing |
所以,我的问题是,如何从Android发送包含标题数据的DELETE请求? 我错过了这一点 - 您是否能够将标题数据添加到DELETE请求中? 谢谢。
有问题的行是
您可以使用
我知道有点晚了,但如果有人像我一样在谷歌搜索我解决了这个问题:
1 2 | conn.setRequestProperty("X-HTTP-Method-Override","DELETE"); conn.setRequestMethod("POST"); |
getOutputStream()仅适用于具有正文的请求,如POST。在没有正文的请求(如DELETE)上使用它将抛出ProtocolException。相反,您应该使用addHeader()添加标头,而不是调用getOutputStream()。
对于旧的Android版本(<= 4.4),这是
虽然您可以使用
我建议使用像OkHttp这样的新的最新库:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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(); } |
DELETE请求是GET请求的扩展形式,根据android文档,您无法在DELETE请求的主体中写入。
HttpUrlConnection将抛出"无法写入协议异常"。
如果您仍想在正文中编写参数,我建议您使用OKHttp库。
OKHttp文档
如果您有兴趣使用更简单的库,那么您可以尝试
SimpleHttpAndroid库
这里要记住的一件事是,如果你没有在身体上写任何东西,那么删除线
1 | conn.setDoOutput(true); |
谢谢,希望它可能有所帮助。
尝试下面的方法来调用HttpDelete方法,它对我有用,希望对你也有用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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(); } |
这是我的
只需
1 | connection.setRequestProperty("X-HTTP-Method-Override","DELETE"); |
下面是完整的方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | 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(); } } } |
我希望它有所帮助。
你不能只使用
为此问题添加闭包,发现没有受支持的方法来发送包含标头数据的HTTP DELETE请求。
解决方案是客户端更改其API以接受标准GET请求,该请求指示该操作应该是删除,包含要删除的项的ID。
1 | http://clienturl.net/api/delete/id12345 |