Httpclient 中经常使用的请求有2个,HttpPost 和 HttpGet,今天在对某个网站进行分析的时候,忽然发现用到了 HttpDelete,而且传参 是 Json。java
一、通常 HttpPost 对传参 Json 的处理是:apache
// 中文处理json
StringEntity se = new StringEntity(json, Consts.UTF_8);浏览器
httppost.setEntity(se);cookie
二、使用 HttpDelete,貌似不能传参,突发奇想,将 HttpDelete 换成 HttpPost,再传参,此路不通。app
三、百度没有找到很好的解决方法。只好 Google, HttpDelete Json,在 stackoverflow 上看了几篇文章,立马找到解决办法了 post
详见 http://stackoverflow.com/questions/3773338/httpdelete-with-body网站
四、解决办法:spa
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(); } }
而后就简单了.net
httpdelete.setHeader("Cookie", cookie);
// json 处理 httpdelete.setHeader("Content-Type", "application/json; charset=UTF-8"); httpdelete.setHeader("X-Requested-With", "XMLHttpRequest"); httpdelete.setEntity(new StringEntity(json)); httpdelete.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000); HttpResponse response = client.execute(httpdelete);
最近 Google 大神很不方便,推荐一款浏览器,Buckyball,大伙自个百度。