设置http请求的类型

时间:2012-01-09 22:05:23

标签: java android http

如何使用org.apache。*库设置http请求的类型?例如,如果我需要 POST 请求:

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

获取

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

工作正常。但是在我的项目中,我只想对所有类型的请求使用一个函数,因为我还需要 PUT DELETE 请求。

那么,如何在 DefaultHttpClient 中设置请求类型,或者(如果不可能)如何创建 PUT DELETE 请求?

3 个答案:

答案 0 :(得分: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 :(得分: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;
   }
}

答案 2 :(得分:1)

List of all the methods.

Put

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

Delete

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