2015-04-29 73 views
-1

我試圖執行HttpDelete,我用HttpGetHttpPost,並且運行良好。Android - 帶JSON的HttpDelete

首先想到的,我看到的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 usuariHttpDelete的實體。我錯過了什麼或者我做錯了什麼?

+0

我不想健全由你爲什麼不嘗試改變一個更完整的HTTP客戶端煩人?有了[Ion](https://github.com/koush/ion),你可以在5,6行代碼中做這種事情。 – 4gus71n

+0

我已經得到所有的POST和GET這個方法...我不想改變我的代碼,我認爲與HttpDelete這是可能的 –

+0

可能重複[HttpDelete與正文](http://stackoverflow.com/ question/3773338/httpdelete-with-body) – 4gus71n

回答

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) 
+0

所以我不能這樣做我的方式嗎? –

+0

這與你所做的一樣。唯一需要做的就是改變這個'HttpDeleteWithBody'的簡單'HttpDelete',這樣就可以讓你通過'setEntity'方法設置json體。 – 4gus71n

+0

在幾個小時內我可以測試它我會說如果它的工作與否;) –