Apache httpclient:教程坏了 - 如何实际使用这个库?

时间:2012-03-09 08:27:48

标签: java apache netbeans ide httpclient

我使用netbeans作为IDE来为您提供背景信息。

我正在使用Apache httpclient库,就像我当前的应用程序一样,我遇到了内置的java HTTP连接问题。

我听说apache库更强大。

无论如何,apache网站上的httpclient库附带的教程文档似乎存在缺陷:

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://localhost/");
HttpResponse response = httpclient.execute(httpget);

Net beans为我提供了此代码段的问题(直接从教程中复制)。忘掉localhost的基本URI,出现的问题是:

  1. netbeans抱怨HttpClient和DefaultHttpClient是不兼容的类型。我能看到的唯一方法就是施放:

    (HttpClient) new DefaultHttpClient(); 
    
  2. Netbeans抱怨httpclient.execute()会抛出错误,因为这里的“httpget”只是一种方法而不是“HttpUriRequest”。
  3. 如果一个简单的3行教程如此错误,如果这个例子中存在很多缺陷,我将如何成功完成一个请求呢?

    我迷路了,有人可以帮帮忙。似乎有几种不同的方式,都不完全是我正在寻找的。

    我希望能够在String中的应用程序中获取格式良好的URL,然后跟随所有重定向。我对响应的内容一点也不感兴趣,只是它会丢弃的cookie。

    谢谢,

    格雷戈里

3 个答案:

答案 0 :(得分:1)

我建议看看你的进口商品。我认为NetBeans导入了你的HttpClient 3.x而不是4.x.尝试更正您的导入。

答案 1 :(得分:0)

您是否尝试过使用此代码,它们似乎使用的机制与您不同。取自here。这适用于3.X版本,因此可能是您使用的是其他版本。

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();
    }  
  }
}

答案 2 :(得分:0)

当我使用它时(在Android上)我实现了一个CustomHttpClient,遵循示例here

相关问题