2012-01-09 80 views
1

如何設置http請求的類型,使用org.apache。* library?例如,如果我需要POST請求設置http請求的類型

HttpPost hp=new HttpPost("http://server.com"); 

GET

HttpGet hg=new HttpGet("http://server.com"); 

它工作正常。但是在我的項目中,我只希望對所有類型的請求使用一個函數,因爲我還需要PUTDELETE請求。

所以,我怎麼能設置的請求類型在DefaultHttpClient或者(如果這是不可能的),我怎麼能創造PUTDELETE請求?

回答

3
HttpMethod httpMethod = new HttpPost("http://server.com"); 

在你常用的功能,您可以使用httpMethod.getName();將返回HTTP召喚你正在做的類型。

語法PUT/DELETE方法是:

HttpMethod httpMethod = new PutMethod("http://server.com"); 
    HttpMethod httpMethod = new DeleteMethod("http://server.com"); 
1

​​

Put

PutMethod put = new PutMethod("http://jakarta.apache.org"); 

Delete

DeleteMethod delete = new DeleteMethod("http://jakarata.apache.org"); 
+0

謝謝。但是,如果不爲每種類型的請求創建對象,都無法解決我的問題?有了這些方法,我將得到4種不同的實現。 – 2012-01-09 22:15:57

2

有可供PUT類似的功能和DELETE請求:

HttpPut hg = new HttpPut("http://server.com"); 
HttpDelete hg = new HttpDelete("http://server.com"); 

http://developer.android.com/reference/org/apache/http/client/methods/HttpPut.html

如果你只需要一個功能你可以創建如下的包裝功能:

public HttpRequestBase httpRequest(String uri, String method) { 
    switch(method) { 
    case "PUT": 
     return new HttpPut(uri); 
    case "DELETE": 
     return new HttpDelete(uri); 
    case "POST": 
     return new HttpPost(uri); 
    case "GET": 
     return new HttpGet(uri); 
    default: 
     return null; 
    } 
}