Android - 带JSON的HttpDelete

时间:2015-04-29 15:48:38

标签: android json

我正在尝试实施HttpDelete,我使用了HttpGetHttpPost,并且运作良好。

首先想一想,我在HttpDelete上看到了这一点,我无法将del.setEntity(entity);置于实体为StringEntity entity = new StringEntity(usuari.toString());usuariJSON的位置。

由于我无法将实体放在我的HttpDelete上,我尝试了这个:

boolean resul = true;
HttpClient httpClient = new DefaultHttpClient();
HttpDelete del = new HttpDelete(getResources().getString(R.string.IPAPI) + "produsuaris/produsuari");

del.setHeader("content-type", "application/json");
try {
    JSONObject usuari = new JSONObject();
    try {
        usuari.put("idProducte", params[0]);
        usuari.put("idusuari", params[1]);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    HttpResponse resp = httpClient.execute(del);
    String respStr = EntityUtils.toString(resp.getEntity());

    if (!respStr.equals("true")) ;
        resul = false;
} catch (Exception ex) {
    Log.e("ServicioRest", "Error!", ex);
}
return resul;

我不知道如何将JSONObject usuari放在HttpDelete的实体上。我错过了什么或我做错了什么?

1 个答案:

答案 0 :(得分:1)

为什么不尝试这样做? IDK确定它是否可行,但值得尝试。

HttpRequestBase dn = new HttpPost() {
                    @Override
                    public String getMethod() {
                        return HttpDelete.METHOD_NAME;
                    }

                    @Override
                    public HttpEntity getEntity() {
                        return new StringEntity("{json}") //Return you raw body here
                    }
                }

你想要做的是发送json作为请求的原始主体,对吧?

你也可以试试这个:

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(); }
}

然后:

HttpDeleteWithBody delete = new HttpDeleteWithBody(api_address);

StringEntity se = new StringEntity(json_data, HTTP.UTF_8);
se.setContentType("application/json");

delete.setEntity(se)