`

HttpClient

 
阅读更多
1:概述

HttpClient是HttpComponents(简称为hc)项目其中的一部份,访问地址:http://hc.apache.org/



HttpClient是一个代码级的Http客户端工具,可以使用它模拟浏览器向Http服务器发送请求。使用HttpClient还需要HttpCore.后者包括Http请求与Http响应的代码封装。



2:HttpGet

    public final static void main(String[] args) throws Exception {
        HttpClient httpclient = new DefaultHttpClient();
        try {
            HttpGet httpget = new HttpGet("http://www.apache.org/");
            System.out.println("executing request " + httpget.getURI());
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            System.out.println("----------------------------------------");

            InputStream inSm = entity.getContent();
            Scanner inScn = new Scanner(inSm);
            while (inScn.hasNextLine()) {
                System.out.println(inScn.nextLine());
            }
            // Do not feel like reading the response body
            // Call abort on the request object
            httpget.abort();
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }
    }




httpcore:EntityUtils.toString(httpEntity)

读取response响应内容部分,也可以借助于 httpcore-4.1.2.jar 里面的
String content = EntityUtils.toString(httpEntity);


具体:
/**
 * User: liuwentao
 * Time: 12-1-25 下午1:23
 */
public class Demo1 {

    /**
     * 用 get 方法访问 www.apache.org 并返回内容
     *
     * @param args
     */
    public static void main(String[] args) {
        //创建默认的 HttpClient 实例
        HttpClient httpClient = new DefaultHttpClient();
        try {
            //创建 httpUriRequest 实例
            HttpGet httpGet = new HttpGet("http://www.apache.org/");
            System.out.println("uri=" + httpGet.getURI());

            //执行 get 请求
            HttpResponse httpResponse = httpClient.execute(httpGet);

            //获取响应实体
            HttpEntity httpEntity = httpResponse.getEntity();
            //打印响应状态
            System.out.println(httpResponse.getStatusLine());
            if (httpEntity != null) {
                //响应内容的长度
                long length = httpEntity.getContentLength();
                //响应内容
                String content = EntityUtils.toString(httpEntity);

                System.out.println("Response content length:" + length);
                System.out.println("Response content:" + content);
            }

            //有些教程里没有下面这行
            httpGet.abort();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭连接,释放资源
            httpClient.getConnectionManager().shutdown();
        }
    }
}


执行结果:



httpget.setHeader

1:分析请求包中这六个头信息



2:代码
    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) {
        HttpClient httpClient = new DefaultHttpClient();
        try {
            HttpGet httpget = new HttpGet("http://www.iteye.com");

            httpget.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            httpget.setHeader("Accept-Language", "zh-cn,zh;q=0.5");
            httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:7.0.1) Gecko/20100101 Firefox/7.0.1)");
            httpget.setHeader("Accept-Encoding", "gzip, deflate");
            httpget.setHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");
            httpget.setHeader("Host", "www.iteye.com");
            httpget.setHeader("Connection", "Keep-Alive");

            HttpResponse response = httpClient.execute(httpget);
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            System.out.println("----------------------------------------");

            InputStream inSm = entity.getContent();
            Scanner inScn = new Scanner(inSm);
            while (inScn.hasNextLine()) {
                System.out.println(inScn.nextLine());
            }
            // Do not feel like reading the response body
            // Call abort on the request object
            httpget.abort();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpClient.getConnectionManager().shutdown();
        }
    }

3:效果



以上乱码是由于
httpget.setHeader("Accept-Encoding", "gzip, deflate");  

注释掉这行,具体:
/**
 * User: liuwentao
 * Time: 12-1-25 下午1:23
 */
public class Demo3 {

    /**
     * 用 get 方法访问 www.baidu.com 并返回内容
     *
     * @param args
     */
    public static void main(String[] args) {
        //创建默认的 HttpClient 实例
        HttpClient httpClient = new DefaultHttpClient();

        try {
            //创建 httpUriRequest 实例
            HttpGet httpGet = new HttpGet("http://www.iteye.com");

            httpGet.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            httpGet.setHeader("Accept-Language", "zh-cn,zh;q=0.5");
            httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:7.0.1) Gecko/20100101 Firefox/7.0.1)");
//            httpGet.setHeader("Accept-Encoding", "gzip, deflate");
            httpGet.setHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");
            httpGet.setHeader("Host", "www.iteye.com");
            httpGet.setHeader("Connection", "Keep-Alive");
            System.out.println("uri=" + httpGet.getURI());

            //执行 get 请求
            HttpResponse httpResponse = httpClient.execute(httpGet);

            //获取响应实体
            HttpEntity httpEntity = httpResponse.getEntity();
            //打印响应状态
            System.out.println(httpResponse.getStatusLine());
            if (httpEntity != null) {
                //响应内容的长度
                long length = httpEntity.getContentLength();
                //响应内容
                String content = EntityUtils.toString(httpEntity);

                System.out.println("Response content length:" + length);
                System.out.println("Response content:" + content);
            }

            //有些教程里没有下面这行
            httpGet.abort();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭连接,释放资源
            httpClient.getConnectionManager().shutdown();
        }
    }
}


效果:


用post方法访问本地应用根据传递参数不同,返回不同结果

web.xml
    <servlet>
        <servlet-name>Test1Servlet</servlet-name>
        <servlet-class>demo.servlet.Test1Servlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Test1Servlet</servlet-name>
        <url-pattern>/test1Servlet</url-pattern>
    </servlet-mapping>


Test1Servlet.java
/**
 * User: liuwentao
 * Time: 11-12-25 下午1:08
 */
public class Test1Servlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //接收地址栏参数
        String param1 = request.getParameter("param1");
        //输出
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write("你传递来的参数param1=" + param1);
        out.close();
    }
}

Demo2.java
/**
 * User: liuwentao
 * Time: 12-1-25 下午1:23
 */
public class Demo2 {

    /**
     * 用post方法访问本地应用根据传递参数不同,返回不同结果
     *
     * @param args
     */
    public static void main(String[] args) {
        //创建默认的 HttpClient 实例
        HttpClient httpClient = new DefaultHttpClient();

        HttpPost httpPost = new HttpPost("http://localhost:86/test1Servlet");

        List<NameValuePair> formParams = new ArrayList<NameValuePair>();
        formParams.add(new BasicNameValuePair("param1", "刘文涛"));
        UrlEncodedFormEntity urlEncodedFormEntity;

        try {
            urlEncodedFormEntity = new UrlEncodedFormEntity(formParams, "UTF-8");
            httpPost.setEntity(urlEncodedFormEntity);
            System.out.println("execurting request:" + httpPost.getURI());
            HttpResponse httpResponse = null;
            httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                String content = EntityUtils.toString(httpEntity, "UTF-8");
                System.out.println("Response content:" + content);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭连接,释放资源
            httpClient.getConnectionManager().shutdown();
        }
    }
}


结果:



  • 大小: 8 KB
  • 大小: 6.2 KB
  • 大小: 21.4 KB
  • 大小: 9 KB
  • 大小: 20.1 KB
  • 大小: 37.5 KB
  • 大小: 13.9 KB
分享到:
评论
5 楼 dyingearth 2014-12-01  
讲得太好了,赞一个
4 楼 java_ganbin 2014-03-25  
文涛兄  来学习了  嘻嘻
3 楼 黑豹1231 2013-11-09  
真的很不错,学习了
2 楼 abc382410124 2013-08-23  
柳暗花明又一村的感觉
1 楼 xiaogaogao 2013-04-15  
,精彩的讲解,收益非浅,学习中

相关推荐

    httpclient.jar包下载

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

    HttpClient4.2.1版本的Jar包

    HttpClient 4.2.1版本引入了一些重要的改进和修复,以提高性能和稳定性。以下是一些关键特性: 1. **连接管理**:HttpClient 4.2.1引入了更完善的连接管理机制,允许开发者控制连接的创建、复用和关闭。`...

    HttpClient 3.x to HttpComponents HttpClient 4.x

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

    httpclient-4.2.5-API文档-中文版.zip

    赠送jar包:httpclient-4.2.5.jar; 赠送原API文档:httpclient-4.2.5-javadoc.jar; 赠送源代码:httpclient-4.2.5-sources.jar; 赠送Maven依赖信息文件:httpclient-4.2.5.pom; 包含翻译后的API文档:httpclient...

    httpclient4.2.1.zip

    本文将深入探讨HttpClient 4.2.1的核心特性和使用方法,帮助开发者更好地理解和应用这个强大的工具。 一、HttpClient简介 HttpClient是一个开放源码的Java库,由Apache软件基金会维护。它为Java程序员提供了一个...

    httpClient

    HttpClient httpClient = new HttpClient(); // 设置 Http 连接超时为5秒 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000); /* 2 生成 GetMethod 对象并设置参数 */ GetMethod ...

    httpclient-4.5.6-API文档-中文版.zip

    赠送jar包:httpclient-4.5.6.jar; 赠送原API文档:httpclient-4.5.6-javadoc.jar; 赠送源代码:httpclient-4.5.6-sources.jar; 赠送Maven依赖信息文件:httpclient-4.5.6.pom; 包含翻译后的API文档:httpclient...

    httpclient

    使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。 1. 创建HttpClient对象。 2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建...

    HttpClientHelper 工具类

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

    HttpClient所需jar包(全) httpClient.4.13jar

    HttpClient 4.13版本是这个库的一个较新版本,包含了一系列的改进和修复。 在Java开发中,HttpClient是一个常用的工具,尤其在处理Web服务或者API调用时。它支持同步和异步操作,可以处理复杂的HTTP协议细节,使...

    httpClient实例httpClient调用 http/https实例 忽略SSL验证

    这个实例主要涉及如何配置HttpClient来忽略SSL(Secure Socket Layer)验证,这对于在开发和测试环境中处理自签名证书或未认证的服务器非常有用。以下将详细介绍HttpClient的使用以及如何进行SSL验证的忽略。 首先...

    httpclient方式调用url

    本篇文章将深入探讨如何使用HttpClient方式调用URL,以及相关的知识点。 首先,HttpClient允许我们构建复杂的HTTP请求,包括GET、POST以及其他HTTP方法。使用HttpClient调用URL的基本步骤包括创建HttpClient实例、...

    httpClient需要的jar包

    本压缩包文件"httpClient"很可能包含了HttpClient库所需的必备JAR文件,这些文件通常包括HttpClient的核心库、依赖的第三方库以及可能的扩展模块。为了正确使用HttpClient,你需要确保将这些JAR文件添加到你的项目类...

    HttpClient 调用WebService示例

    在本文中,我们将深入探讨如何使用HttpClient调用WebService。 首先,调用WebService通常涉及SOAP(Simple Object Access Protocol)或RESTful API。HttpClient可以处理这两种类型的Web服务。在本示例中,我们假设...

    httpclient-4.5.5-API文档-中文版.zip

    赠送jar包:httpclient-4.5.5.jar; 赠送原API文档:httpclient-4.5.5-javadoc.jar; 赠送源代码:httpclient-4.5.5-sources.jar; 包含翻译后的API文档:httpclient-4.5.5-javadoc-API文档-中文(简体)版.zip ...

    httpclient-4.5.13-API文档-中英对照版.zip

    赠送jar包:httpclient-4.5.13.jar; 赠送原API文档:httpclient-4.5.13-javadoc.jar; 赠送源代码:httpclient-4.5.13-sources.jar; 赠送Maven依赖信息文件:httpclient-4.5.13.pom; 包含翻译后的API文档:...

    HTTPClient

    ### HTTPClient知识点详解 #### 1. HttpClient4 – 获取状态码 **1.1 概览** 本节将详细介绍如何使用HttpClient 4.x版本来获取HTTP响应的状态码,并对其进行验证。这对于开发人员来说是一个非常实用的功能,可以...

    httpClient组合包.zip

    此外,HttpClient还支持异步操作,可以在多线程环境中高效地处理并发请求。 2. **httpcore-4.4.12.jar**:这是HttpClient的核心库,包含了HTTP协议的基本组件,如连接管理、请求和响应模型、编码器和解码器等。...

    Java HttpClient 全部的jar包

    在Java项目中,使用HttpClient可以实现与Web服务器的高效通信。下面将详细介绍这12个jar包的作用及其在HttpClient中的功能: 1. `commons-beanutils-1.8.0.jar`: Apache Commons BeanUtils库提供了对Java Beans属性...

    Arduino HttpClient 库文件

    1. **实例化 HttpClient 对象**:首先,你需要创建一个 `HttpClient` 类的实例,例如 `HttpClient client;` 2. **设置服务器信息**:调用 `client.begin()` 函数,传入你要访问的服务器地址和端口号,如 `client....

Global site tag (gtag.js) - Google Analytics