论坛首页 Java企业应用论坛

HttpClient 使用

浏览 9068 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-02-22   最后修改:2009-02-22
http://hc.apache.org/httpclient-3.x/
   HttpClient 是作为Jakarta Commons的子项目从2001年开始的,以Jakarta slide项目开发的代码为基础。2004年成为独立的项目.
   下面是它的简单使用,更多信息可以参考上面的链接:
实例化HttpClient
HttpClient client = new HttpClient();
生成方法
有很多实现了HttpMthod的接口的方法类,下面介绍的是最简单的一种,它的作用是取到url指定的文档:
HttpMethod method = new GetMethod("http://www.apache.org/");
执行方法:
client.executeMethod(method);

这就是基本过程,下面是官方网站的一段代码:
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();
    }  
  }
}
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics