`

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

    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请求,创建...

    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-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文档:...

    可用org.apache.commons.httpclient-3.1.0.jar.zip

    import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods....

    httpclient-4.5jar

    httpclient-4.5所需jar包,里面包含httpclient-4.5.jar等等10个必须的开发包。 1.commons-codec-1.9.jar 2.commons-logging-1.2.jar 3.fluent-hc-4.5.jar 4.httpclient-4.5.jar 5.httpclient-cache-4.5.jar 6....

    httpclient4.5.3 jar完整包含所有依赖包

    HttpClient 4.5.3 (GA) is a maintenance release that fixes a number of defects found since 4.5.2. Please note that as of 4.4 HttpClient requires Java 1.6 or newer. Changelog: ------------------- * ...

    httpclient.jar包下载

    httpclient.jar下载 包括code.jar包

    SpringBoot使用httpclient发送Post请求时

    try(CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost(url); StringEntity stringEntity = new StringEntity(params, Charset.forName("UTF-8")); ...

    Android_HttpClient_jar包

    Android使用HttpClient发送请求、接收响应很简单,只要如下几步即可: Step1:创建HttpClient对象; Step2:如果需要发送GET请求,则创建HttpGet对象; 如果需要发送POST请求,则创建HttpPost对象; Step3:如果...

    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...

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

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

    HttpClient以及获取页面内容应用

    压缩包中含有多个文档,从了解httpclient到应用。 httpClient 1httpClint 1.1简介 HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持...

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

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

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

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

    HttpClient 3.x to HttpComponents HttpClient 4.x

    帮助程序员快速从Apache的HttpClient 3.x升级到HttpClient 4.x

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

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

Global site tag (gtag.js) - Google Analytics