`
lokvin
  • 浏览: 164877 次
  • 性别: Icon_minigender_1
  • 来自: 地球
文章分类
社区版块
存档分类
最新评论

HttpClient simple turorial

阅读更多
this from HttpClient document.
HttpClinet now version is 3.1 ,come from apache.
it dependcy lib: commons loging,commons codec

How to use HttpClinet
1.create an instance of HttpClient
2.create an instance of one of the methods
3.tell the HttpClient to execute the method
4.read the response
5.release the connection
6.deal with the response

Notice that we go through the entire process regardless of whether
the server returned an error or not. This is important because
Http 1.1 allows multiple requests to use the same connection by
simply sending the requests one after another. Obviously, if we
don't read the entire response to the first request, the left over
data will get in the way of the second response. HttpClient try to
handle this but to avoid problem ,it is important to always the
connection.

HttpClient client = new HttpClient();

HttpMethod method = new GetMethod("http://www.google.cn");


executeMethod()
Since the network connection are unreliable. We also deal with any
errors that occur.
executeMethod() throws 2 type exception, HttpException,IOException

HttpException is sub class of IOException, it represents a fatal error
, it usually can't be recoverd.

a plain IOException represents a transport error. so per default HttpClient
will try to recover the request automatilly , default 3 times.

read the response
It's vital that the response body is always read regardless of the status returned by the server.
3 ways to do this:

method.getResponseBody(); return a byte array
method.getResponseBodyAsString(); return a String. conversion from bytes to String using default encoding.
method.getResponseBodyAsStream(); this method is best if it is possible for a lot of data to be received.
as it can be buffered to a file or
processed as it is read.

release the connection
This is a crucial step. We must tell HttpClient that we are done with
the connection .

method.releaseConnection();


all code for this:

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.google.cn/";

  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();
    }  
  }
}
分享到:
评论

相关推荐

    httpclient-tutorial开发指导文档.pdf

    文档详细介绍了HttpClient接口,包括它的线程安全性(Thread Safety)和资源释放(Resource Deallocation)机制。这对于开发者来说非常重要,因为它关系到如何正确地管理HttpClient实例,以避免资源泄露和线程安全...

    httpclient-tutorial-simplified-chinese

    ### HttpClient教程概览 #### 一、基础知识 **1.1 执行请求** - **HTTP 请求**:HTTP 请求包括请求行、请求头和可能的消息体。请求行包含方法(如GET、POST)、请求URI和HTTP版本。请求头包含了客户端希望服务器...

    httpclient-tutorial.pdf

    以上是对“httpclient-tutorial.pdf”文档的概括,涵盖了HTTP客户端的基础知识、连接管理、状态管理以及HTTP认证等核心知识点。通过深入理解这些内容,开发者可以更好地掌握如何在Android应用中实现高效的网络通信...

    httpclient-tutorial开发指导文档.zip

    《HttpClient教程:深入理解与应用》 HttpClient是Java领域中广泛使用的HTTP客户端库,它提供了丰富的功能,使得开发者能够方便地进行HTTP通信。本教程将深入解析HttpClient的主要特性和使用方法,帮助你全面掌握这...

    httpclient tutorial httpclient 指南

    httpclient 指南 包括了详细的调用和常用代码 The Hyper-Text Transfer Protocol (HTTP) is perhaps the most significant protocol used on the Internet today. Web services, network-enabled appliances and the...

    httpclient-tutorial

    从提供的文件信息中,可以提取出关于HttpClient教程的知识点。HttpClient是Apache HTTP Components项目中用于Java的一个重要的客户端HTTP连接库,广泛用于网络编程,特别是网络爬虫的开发。以下是对文件内容的详细...

    HttpClient4_Tutorial_API_Doc_En+Cn.rar

    最后,“httpclient-tutorial.pdf”可能是另一份关于HttpClient的教程,它可能更侧重于实战应用,包括与服务器的交互、错误处理、性能优化等方面。教程可能还会讨论如何集成HttpClient到Spring框架中,或者如何在...

    httpclient tutorial

    ### HTTPClient 教程知识点详解 #### 一、概述与基本概念 **1.1 请求执行** - **HTTP请求:** HTTP请求是客户端向服务器发送的一条消息,它包括一个方法(例如GET或POST)、一个URL、可能还有一组头字段(headers...

    httpclient资料

    在HttpClient-tutorial.pdf中,我们可以了解到HttpClient的基本用法和高级特性。教程将涵盖如何初始化HttpClient实例,设置请求头,发送GET和POST请求,以及如何处理响应。同时,它也会讲解如何配置连接管理器以优化...

    httpclient.jar包下载

    《深入解析httpclient.jar及其与code.jar的关联》 在Java开发中,HTTP通信是不可或缺的一部分,而Apache HttpClient库正是Java实现HTTP客户端操作的重要工具。本文将深入探讨httpclient.jar包,以及它与code.jar包...

    HttpClient 调用WebService示例

    首先,调用WebService通常涉及SOAP(Simple Object Access Protocol)或RESTful API。HttpClient可以处理这两种类型的Web服务。在本示例中,我们假设你正在使用SOAP,因为通常需要发送XML格式的数据到WebService。 ...

    httpclient httpclient.jar

    在本文中,我们将深入探讨HttpClient的核心概念、使用方法以及如何通过`httpclient.jar`进行实战应用。 首先,HttpClient的主要组件包括: 1. **HttpClient实例**:这是整个HTTP通信的核心,负责管理连接、请求和...

    HttpClientHelper 工具类

    HttpClientHelper 对这个类进行了封装,使得开发者无需直接与HttpClient接口打交道,而是通过更简洁、易用的方法调用来实现网络通信。这提高了代码的可读性和可维护性。 单例模式是软件设计模式的一种,确保一个类...

    HttpClient4.1.2中英文文档

    在《HttpClient Tutorial》中,你可以学习到以下关键知识点: - **初始化HttpClient**:了解如何创建HttpClient实例,设置基本配置,如默认主机名验证、超时设置等。 - **执行HTTP请求**:学习如何构造HttpGet、...

    HttpClient 3.x to HttpComponents HttpClient 4.x

    例如,在HttpClient 3.x中,代码可能会使用`***mons.httpclient.HttpClient`类和`***mons.httpclient.methods.GetMethod`等,而在4.x版本中,这些都被新的API所替代。程序员需要熟悉`org.apache....

    httpclient

    创建HttpClient实例是使用HttpClient的第一步。通常,我们会创建一个`CloseableHttpClient`对象,这可以通过`HttpClientBuilder`或者`HttpAsyncClientBuilder`来实现。例如: ```java CloseableHttpClient ...

Global site tag (gtag.js) - Google Analytics