Httpclient 中常用的请求有2个,HttpPost 和 HttpGet,今天在对某个网站进行分析的时候,突然发现用到了 HttpDelete,并且传参 是 Json。
1、一般 HttpPost 对传参 Json 的处理是:
// 中文处理
StringEntity se = new StringEntity(json, Consts.UTF_8);
httppost.setEntity(se);
2、使用 HttpDelete,貌似不能传参,突发奇想,将 HttpDelete 换成 HttpPost,再传参,此路不通。
3、百度没有找到很好的解决方法。只好 Google, HttpDelete Json,在 stackoverflow 上看了几篇文章,立马找到解决办法了
详见 http://stackoverflow.com/questions/3773338/httpdelete-with-body
4、解决办法:
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(); } }
然后就简单了
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,大伙自个百度。