2015-08-24 14 views
0

當我通過捲曲執行此其工作:Groovy:在無法設置請求主體用於刪除/ GET方法

curl -u -X DELETE -H 'accept:application/json' http://localhost:13000/test/test_userid" 

我製成,其接受methodtype(GET,POST,DELETE等)共同的功能和內容類型(JASON,TEXT)爲httpbuilder。

def public httpRequest(String url, String content, Method requestType, ContentType contentType) 
{ 
     try{ 
      def myClient = new HTTPBuilder(url) 
      myClient.request(requestType,contentType) { req ->   
      headers.'Content-Type' = 'application/json' 
      body=content 
      response.success = { resp, data ->   
       def reponse=[resp:resp,data:data] 
       return reponse 
      } 

      response.failure = { resp -> 
       println 'Response Code '+resp.statusLine 
      } 
      // called only for a 404 (not found) status code: 
      response.'404' = { resp -> 
       println 'Not found' 
      } 
      } 
     } 
     catch(Exception e) 
     { 
      println "error"+e.getProperties() 
     } 
} 

現在,如果我提出POST請求,它的工作。 但是,如果我做一個GET或使用

def response = httpRequest(url,"",DELETE,JSON) 

def response = httpRequest(url,"",GET,TEXT) 

它顯示了以下錯誤DELETE請求: -

error[message:Cannot set a request body for a DELETE/GET method, class:class java.lang.IllegalArgumentException 

我是否需要做一個單獨的功能GET /刪除? 因爲

myClient.request(requestType) { req ->   
      headers.'Content-Type' = 'application/json' 
      body=content 
      response.success = { resp, data ->   
       def reponse=[resp:resp,data:data] 
       return reponse 
      } 

      response.failure = { resp -> 
       println 'Response Code '+resp.statusLine 
      } 
      // called only for a 404 (not found) status code: 
      response.'404' = { resp -> 
       println 'Not found' 
      } 
      } 
     } 

WORKS

+0

我不相信GET請求應該有一個身體HTTP ://stackoverflow.com/questions/978061/http-get-with-request-body –

+0

是的,它似乎我必須做一個單獨的功能呢。謝謝 –

回答

0

刪除和獲取不會接受體,因此該解決方案是使檢查和相應的執行

if(requestType.equals(DELETE)||requestType.equals(GET)) 
     { 
      try{ 
       def myClient = new HTTPBuilder(url) 
       myClient.request(requestType) { req ->   
       headers.'Content-Type' = 'application/json' 
       headers.Accept = 'application/json' 
       response.success = { resp, data ->   
        def reponse=[resp:resp,data:data] 
        return reponse 
       } 

       response.failure = { resp -> 
        println 'Response Code '+resp.statusLine 
       } 
       // called only for a 404 (not found) status code: 
       response.'404' = { resp -> 
        println 'Not found' 
       } 
       } 
      } 
      catch(Exception e) 
      { 
       println "error"+e.getProperties() 
      } 
     } 
    else 
    <---post request -->