什么是Http GetMethod(String URI)构造函数

时间:2013-10-28 05:51:56

标签: java apache

我已经从apache.org链接阅读了关于GetMethod的documnet http://hc.apache.org/httpclient-legacy/tutorial.html,但我没有得到足够的信息。有人可以解释一下这个方法何时应该用一个简单的例子。

3 个答案:

答案 0 :(得分:0)

当您要为URI创建HTTP GET请求时,使用GetMethod(String URI)。 documentation中的以下示例解释了所有内容。

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.*;

public class HttpClientTutorial {

  private static String url = "http://www.apache.org/";

  public static void main(String[] args) {
    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod(url);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
            new DefaultHttpMethodRetryHandler(3, false));

    try {
      // Execute the method.
      int statusCode = client.executeMethod(method);

      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + method.getStatusLine());
      }

      // Read the response body.
      byte[] responseBody = method.getResponseBody();

      // Deal with the response.
      // Use caution: ensure correct character encoding and is not binary data
      System.out.println(new String(responseBody));

    } catch (HttpException e) {
      System.err.println("Fatal protocol violation: " + e.getMessage());
      e.printStackTrace();
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    } finally {
      // Release the connection.
      method.releaseConnection();
    }  
  }
}

请阅读评论以便清楚了解。希望这有帮助

答案 1 :(得分:0)

GetMethod实际上实现了HTTP GET方法。因此,如果您要将HTTP GET请求发送到某个URL,那么您应该使用它。

答案 2 :(得分:0)

GetMethod接受HTTP Get请求,其中url是一个查询字符串,因为它出现在url中,例如当你提交一个表单时,包含userName和password以及关于登录url的操作,url appars as

的http:// [应用名] /登录用户名= prawin&安培;密码= 123

- 建议您在发送保密信息时使用帖子。 谢谢。