2012-04-10 199 views
4

我正在爲刪除API的服務器編寫客戶端代碼。 API規範要求發送數據。我正在使用HttpComponents v3.1庫來編寫客戶端代碼。使用HtpDelete類,我找不到向其添加請求數據的方法。有沒有辦法做到這一點?以下是代碼片段。如何爲Http Delete方法設置RequestBody。

 HttpDelete deleteReq = new HttpDelete(uriBuilder.toString()); 
    List<NameValuePair> postParams = new ArrayList<NameValuePair>(); 
    postParams.add(new BasicNameValuePair(RestConstants.POST_DATA_PARAM_NAME, 
      postData.toString())); 
    try { 
     UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams); 
     entity.setContentEncoding(HTTP.UTF_8); 
     //deleteReq.setEntity(entity); // There is no method setEntity() 
     deleteReq.setHeader(RestConstants.CONTENT_TYPE_HEADER, RestConstants.CONTENT_TYPE_HEADER_VAL); 
    } catch (UnsupportedEncodingException e) { 
     logger.error("UnsupportedEncodingException: " + e); 
    } 

在此先感謝。

+0

出於好奇:什麼API是什麼? (需要一個DELETE請求體) – 2012-04-10 20:09:53

+0

它是一個自定義的第三方REST API。 :) – 2012-04-10 21:05:17

回答

7

我還沒有嘗試過這個,它和地獄一樣瘋狂,如果事實證明有更好的解決方案,我會感到更高興,但是您可能會嘗試擴展PostMetod並重寫getName()方法以返回「DELETE」 。

9

爲什麼不能做到這一點:-)

class MyHttpDelete extends HttpPost{ 
    @Override 
    public String getMethod() { 
     return "DELETE"; 
    } 
} 
相關問題