Android 带正文的 HttpDelete
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3773338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HttpDelete with body
提问by Andrew
I'm attempting to use an HttpDelete object to invoke a web service's delete method. The web service's code parses JSON from the message's body. However, I'm failing to understand how to add a body to an HttpDelete object. Is there a way to do this?
我正在尝试使用 HttpDelete 对象来调用 Web 服务的删除方法。Web 服务的代码从消息的正文中解析 JSON。但是,我无法理解如何将主体添加到 HttpDelete 对象。有没有办法做到这一点?
With HttpPut and HttpPost, I call the setEntity method and pass in my JSON. There doesn't appear to be any such method for HttpDelete.
使用 HttpPut 和 HttpPost,我调用 setEntity 方法并传入我的 JSON。HttpDelete 似乎没有任何此类方法。
If there is no way to set a body for an HttpDelete object, could you please link me to a resource that uses a super class of HttpDelete such that I can set the method (delete) and set a body. I know that isn't ideal, but at this point I can't alter the web service.
如果无法为 HttpDelete 对象设置主体,请您将我链接到使用 HttpDelete 超类的资源,以便我可以设置方法(删除)并设置主体。我知道这并不理想,但此时我无法更改 Web 服务。
回答by Walter Mundt
Have you tried overriding HttpEntityEnclosingRequestBase
as follows:
您是否尝试过HttpEntityEnclosingRequestBase
如下覆盖:
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import java.net.URI;
import org.apache.http.annotation.NotThreadSafe;
@NotThreadSafe
class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
public static final String METHOD_NAME = "DELETE";
public String getMethod() { return METHOD_NAME; }
public HttpDeleteWithBody(final String uri) {
super();
setURI(URI.create(uri));
}
public HttpDeleteWithBody(final URI uri) {
super();
setURI(uri);
}
public HttpDeleteWithBody() { super(); }
}
That will create a HttpDelete
-lookalike that has a setEntity
method. I think the abstract class does almost everything for you, so that may be all that's needed.
这将创建一个HttpDelete
具有setEntity
方法的-lookalike 。我认为抽象类几乎可以为您完成所有工作,因此这可能就是您所需要的。
FWIW, the code is based on this source to HttpPost that Google turned up.
FWIW,该代码基于Google 提供的 HttpPost 来源。
回答by dazito
Following Walter Mudnt advice, you can use this code. It works, just made it while testing my REST webservice.
按照 Walter Mudnt 的建议,您可以使用此代码。它有效,只是在测试我的 REST web 服务时成功了。
try {
HttpEntity entity = new StringEntity(jsonArray.toString());
HttpClient httpClient = new DefaultHttpClient();
HttpDeleteWithBody httpDeleteWithBody = new HttpDeleteWithBody("http://10.17.1.72:8080/contacts");
httpDeleteWithBody.setEntity(entity);
HttpResponse response = httpClient.execute(httpDeleteWithBody);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
To access the response you can simply do: response.getStatusLine();
要访问响应,您只需执行以下操作: response.getStatusLine();
回答by Oleg
There are different interpretation in the question whether the body is allowed or not in the HTTP DELETE
request. See thisfor example. In the HTTP 1.1 specificationit is not explicitly prohibied. In my opinion you should not use bodyin the HTTP DELETE
.
对于HTTP DELETE
请求中是否允许主体的问题,存在不同的解释。请参阅此示例。在HTTP 1.1 规范中没有明确禁止。我认为你不应该在HTTP DELETE
.
Nevertherless I think that you should use URL like mysite/myobject/objectId
(shop.com/order/1234
) where the objectId
(a part of the url) is the additional information. As an alternative you can use URL parameters: mysite/myobject?objectName=table&color=red
to send additipnal information to the server in the HTTP DELETE
request. The part starting with '?' is the urlencodedparameters devided dy '&'.
尽管如此,我认为您应该使用像mysite/myobject/objectId
( shop.com/order/1234
) 这样的URL ,其中objectId
(url 的一部分)是附加信息。作为替代方案,您可以使用URL 参数:mysite/myobject?objectName=table&color=red
在HTTP DELETE
请求中向服务器发送附加信息。以'?'开头的部分 是通过dy '&' 划分的urlencoded参数。
If you want to send more complex information you can convert the data to JSON with respect of DataContractJsonSerializeror JavaScriptSerializerand then send the converted data (a string which I name myJsonData
later) also as the parameter: mysite/myobject?objectInfo=myJsonData
.
如果您想发送更复杂的信息,您可以将数据转换为关于DataContractJsonSerializer或JavaScriptSerializer 的JSON,然后将转换后的数据(我myJsonData
稍后命名的字符串)也作为参数发送:mysite/myobject?objectInfo=myJsonData
。
If you need to send too much additionnal data as a part of HTTP DELETE
request so that you have problem with the URL length then you should probably better change the design of your application.
如果您需要在请求中发送过多的附加数据,HTTP DELETE
从而导致 URL 长度出现问题,那么您最好更改应用程序的设计。
UPDATED: Iy you do want send some body per HTTP DELETE you can do this for example like following
更新:您确实希望每个 HTTP DELETE 发送一些正文,您可以执行此操作,例如如下
// somewhere above add: using System.Net; and using System.IO;
WebClient myWebClient = new WebClient ();
// 1) version: do simple request
string t= myWebClient.UploadString ("http://www.examples.com/", "DELETE", "bla bla");
// will be send following:
//
// DELETE http://www.examples.com/ HTTP/1.1
// Host: www.examples.com
// Content-Length: 7
// Expect: 100-continue
// Connection: Keep-Alive
//
//bla bla
// 2) version do complex request
Stream stream = myWebClient.OpenWrite ("http://www.examples.com/", "DELETE");
string postData = "bla bla";
byte[] myDataAsBytes = Encoding.UTF8.GetBytes (postData);
stream.Write (myDataAsBytes, 0, myDataAsBytes.Length);
stream.Close (); // it send the data
// will be send following:
//
// DELETE http://www.examples.com/ HTTP/1.1
// Host: www.examples.com
// Content-Length: 7
// Expect: 100-continue
//
// bla bla
// 3) version
// create web request
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create ("http://www.examples.com/");
webRequest.Method = "DELETE";
webRequest.ServicePoint.Expect100Continue = false;
// post data
Stream requestStream = webRequest.GetRequestStream ();
StreamWriter requestWriter = new StreamWriter (requestStream);
requestWriter.Write (postData);
requestWriter.Close ();
//wait for server response
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse ();
// send following:
// DELETE http://www.examples.com/ HTTP/1.1
// Host: www.examples.com
// Content-Length: 7
// Connection: Keep-Alive
//
// bla bla
the full code could be a little more complex, but this one already will work. Nevertheless I continue to say that Web Service needed data in the body of HTTP DELETE request is bad designed.
完整的代码可能会稍微复杂一些,但这个已经可以工作了。尽管如此,我还是要说 HTTP DELETE 请求正文中 Web 服务所需的数据设计得很糟糕。
回答by Ishan Liyanage
use this,
用这个,
class MyDelete extends HttpPost{
public MyDelete(String url){
super(url);
}
@Override
public String getMethod() {
return "DELETE";
}
}
回答by HopefullyHelpful
in retrofit
改造中
import okhttp3.Request;
private final class ApiInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request oldRequest = chain.request();
Request.Builder builder = oldRequest.newBuilder();
if(condition) {
return chain.proceed(builder.build().newBuilder().delete(builder.build().body()).build());
}
return chain.proceed(builder.build());
}
}
you have to trigger condition, via something and potentially have to do some filtering for the url/header/body to remove the trigger,
您必须通过某些方式触发条件,并且可能必须对 url/header/body 进行一些过滤以删除触发器,
unless the delete url/body/header is unique enough to not collide with post or get requests.
除非删除 url/body/header 足够独特,不会与 post 或 get 请求发生冲突。