HttpDelete与身体

And*_*rew 40 android httpclient webservice-client http-delete

我正在尝试使用HttpDelete对象来调用Web服务的delete方法.Web服务的代码从消息的正文中解析JSON.但是,我无法理解如何向HttpDelete对象添加主体.有没有办法做到这一点?

使用HttpPut和HttpPost,我调用setEntity方法并传入我的JSON.HttpDelete似乎没有任何此类方法.

如果无法为HttpDelete对象设置主体,请将我链接到使用超类HttpDelete的资源,以便我可以设置方法(删除)并设置主体.我知道这不太理想,但此时我无法改变网络服务.

Wal*_*ndt 93

您是否尝试过覆盖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(); }
}
Run Code Online (Sandbox Code Playgroud)

这将创建一个HttpDeletesetEntity方法的-lookalike .我认为抽象类几乎可以为你做所有事情,所以这可能就是所需要的.

FWIW,代码是基于谷歌出现的HttpPost的这个来源.

  • 你摇滚老兄!谢谢! (4认同)

daz*_*ito 9

按照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();
    }
Run Code Online (Sandbox Code Playgroud)

要访问响应,您只需执行以下操作: response.getStatusLine();