• HttpClient(一)


    简介:
    HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。HttpClient 已经应用在很多的项目中,比如 Apache Jakarta 上很著名的另外两个开源项目 Cactus 和 HTMLUnit 都使用了 HttpClient。

    几个重要的类:
    HttpClient  --------------    HttpClient代表了一个http的客户端,HttpClient接口定义了大多数基本的http请求执行行为。
    HttpEntity  --------------    entity是发送或者接收消息的载体,entities 可以通过request和response获取到。
    HttpConnection ---------    HttpConnection代表了一个http连接。

     1 HttpClient httpclient = new DefaultHttpClient();
     2     try {
     3         // 创建httpget.
     4         HttpGet httpget = new HttpGet("http://www.baidu.com/");
     5         System.out.println("executing request " + httpget.getURI());
     6         // 执行get请求.
     7         HttpResponse response = httpclient.execute(httpget);
     8         // 获取响应实体
     9         HttpEntity entity = response.getEntity();
    10         System.out.println("--------------------------------------");
    11         // 打印响应状态
    12         System.out.println(response.getStatusLine());
    13         if (entity != null) {
    14         // 打印响应内容长度
    15         System.out.println("Response content length: "
    16             + entity.getContentLength());
    17         // 打印响应内容
    18         System.out.println("Response content: "
    19             + EntityUtils.toString(entity));
    20         }
    21         System.out.println("------------------------------------");
    22     }catch(Exception e){
    23         e.printStackTrace();
    24     } finally {
    25         // 关闭连接,释放资源
    26         httpclient.getConnectionManager().shutdown();
    27     }

    打印结果:
    executing request http://localhost:8080/struts2/
    --------------------------------------
    HTTP/1.1 200 OK
    Response content length: 395
    Response content:

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Insert title here</title>
    </head>
    <body>
    <form action="user!login.action" method="post">
    <input type="text" name="msg" />
    <input type="submit" value="submit"/>
    </form>
    </body>
    </html>
    ------------------------------------

  • 相关阅读:
    emulate sh
    postmaster.c 中的 ListenAddresses
    PostgreSQL的postmaster的fork动作验证
    NotifyMyFrontEnd 函数背后的数据缓冲区(三)
    对${ZSH_VERSION+set}的验证
    微软正准备一个简易的Rootkit清除方案 助用户打补丁 狼人:
    创新与安全:云计算的两只跷跷板 狼人:
    苹果禁止iPhone黑客访问App Store应用商店 狼人:
    春节不回家 单身留守族“拼饭”“拼玩” 狼人:
    僵尸侵入全球 袭击者或为东欧黑帮 狼人:
  • 原文地址:https://www.cnblogs.com/xuekyo/p/2573653.html
Copyright © 2020-2023  润新知