Chinaunix首页 | 论坛 | 博客
  • 博客访问: 414803
  • 博文数量: 116
  • 博客积分: 7087
  • 博客等级: 少将
  • 技术积分: 1175
  • 用 户 组: 普通用户
  • 注册时间: 2005-02-19 23:32
文章分类

全部博文(116)

文章存档

2012年(1)

2011年(2)

2010年(10)

2009年(21)

2008年(18)

2007年(12)

2006年(21)

2005年(31)

我的朋友

分类:

2005-12-22 12:48:53

以前写过一些通过程序访问网站的应用,但是很可惜,只能用于windows平台.

一直都想找跨平台的方法,今天被我找到了.那就是apache的httpclient 3.0

apache的东东还真是丰富,居然提供了一个java写的库,可以方便我们开发访问web网站的应用.

今天利用httpclient写了一个小程序.该程序可以访问网站的首页.特别支出在于,它支持NTLM身份验证. 因为,某些网站,如果不能够提供有效的身份验证,是无法看到任何信息的.

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

import java.io.*;

public class HttpClientTutorial {
 
  private static String url = "";

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

    NTCredentials defaultcreds = new NTCredentials("mac-username", "mac-password","mac-hostname","mac-domain");
    client.getState().setCredentials(new AuthScope("10.8.0.219", 80, AuthScope.ANY_REALM), defaultcreds);
   
   
    // 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();
    } 
  }
}

编译的时候需要注意,它用到了apache提供的httpclient库,所以要这样做:

javac -cp "/home/sb/commons-httpclient-3.0.jar" HttpClientTutorial.java

运行的时候更加复杂

java -cp "/home/sb/commons-httpclient-3.0.jar:/home/sb/commons-codec-1.3.jar:/home/sb/commons-logging.jar:." HttpClientTutorial

这些jar文件都可以从apache.org下载.

阅读(892) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~