【问题标题】:Android - HttpDelete with JSONAndroid - 带有 JSON 的 HttpDelete
【发布时间】:2015-04-29 15:48:38
【问题描述】:

我正在尝试实现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 的实体上。我错过了什么或做错了什么?

【问题讨论】:

  • 我不想听起来烦人,你为什么不尝试改用更完整的 http 客户端呢?使用Ion,您可以在 5,6 行代码中完成此类操作。
  • 我已经用这个方法得到了所有的 POST 和 GET ......我不想改变我的代码,我认为使用 HttpDelete 是可能的
  • HttpDelete with body的可能重复

标签: android json


【解决方案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)

【讨论】:

  • 所以我不能按我的方式做?
  • 这和你做的一样。。你唯一需要做的就是改变简单的HttpDelete 这个HttpDeleteWithBody 这样做可以让你通过setEntity 方法。
  • 第一件事是什么?我的意思是,我创建了类,然后我什么时候必须创建 JSON?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-12
  • 1970-01-01
  • 1970-01-01
  • 2014-11-05
  • 2023-03-26
相关资源
最近更新 更多