zoukankan      html  css  js  c++  java
  • 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>
    ------------------------------------

  • 相关阅读:
    POJ 1141 括号匹配 DP
    881. Boats to Save People
    870. Advantage Shuffle
    874. Walking Robot Simulation
    文件操作
    861. Score After Flipping Matrix
    860. Lemonade Change
    842. Split Array into Fibonacci Sequence
    765. Couples Holding Hands
    763. Partition Labels
  • 原文地址:https://www.cnblogs.com/xuekyo/p/2573653.html
Copyright © 2011-2022 走看看