2012-01-09 86 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; 
    } 
}