利用HttpClient4访问网页

利用HttpClient4访问网页

1、HttpClient介绍html

  虽然在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能,可是它没有提供足够的灵活性和其余应用程序须要的功能。HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,而且它支持 HTTP 协议最新的版本和建议。java

2、使用范例(如下版本4.3)编程

1,经过get方式,请求网页内容。咱们首先建立httpclient对象,而后经过httpclient来执行http get方法,httpresponse得到服务端响应的全部内容,httpentity为获取的网页消息体。数组

ExpandedBlockStart.gif
复制代码
        CloseableHttpClient httpclient = HttpClients.createDefault();        try {            // 以get方法执行请求
            HttpGet httpGet = new HttpGet(“http://localhost/”);            // 得到服务器响应的全部信息
            CloseableHttpResponse responseGet = httpclient.execute(httpGet);            try {                System.out.println(responseGet.getStatusLine());                // 得到服务器响应的消息体(不包括http head)
                HttpEntity entity = responseGet.getEntity();                if (entity != null) {                    // 得到响应字符集编码
                    ContentType contentType = ContentType.getOrDefault(entity);                    Charset charset = contentType.getCharset();                    InputStream is = entity.getContent();                    // 将inputstream转化为reader,并使用缓冲读取,还可按行读取内容
                    BufferedReader br = new BufferedReader(                            new InputStreamReader(is, charset));                    String line = null;                    while ((line = br.readLine()) != null) {                        System.out.println(line);                    }                    is.close();                }            } finally {                responseGet.close();            }        } finally {            httpclient.close();        }
复制代码

2,经过post方式提交表单。浏览器可将登陆后的会话信息存储到本地,登录以后的每次请求都会自动向服务器发送cookie信息,幸亏的是httpclient亦可自动处理cookie信息。浏览器

ExpandedBlockStart.gif
复制代码
        CloseableHttpClient httpclient = HttpClients.createDefault();            // 以post方法发起登陆请求
            String urlString = "http://localhost/llogin.do";            HttpPost httpPost = new HttpPost(urlString);            List<NameValuePair> nvps = new ArrayList<NameValuePair>();            nvps.add(new BasicNameValuePair("username", "admin"));            nvps.add(new BasicNameValuePair("password", "admin"));            // 添加post参数
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));            CloseableHttpResponse response = httpclient.execute(httpPost);            try {                // 状态302的话,重定向,则没法获取响应消息体                System.out.println(response.getStatusLine());                // 得到服务器响应的消息体(不包括http head)
                HttpEntity entity = response.getEntity();                if (entity != null) {                    // 得到响应字符集编码
                    ContentType contentType = ContentType.getOrDefault(entity);                    Charset charset = contentType.getCharset();                    InputStream is = entity.getContent();                    // 将inputstream转化为reader,并使用缓冲读取,还可按行读取内容
                    BufferedReader br = new BufferedReader(                            new InputStreamReader(is, charset));                    String line = null;                    while ((line = br.readLine()) != null) {                        System.out.println(line);                    }                    is.close();                }            } finally {                response.close();            }
复制代码

3,重定向。httpclient默承认自动处理重定向请求,可是post方式需另外设置。服务器

ExpandedBlockStart.gif
复制代码
        LaxRedirectStrategy redirectStrategy = new LaxRedirectStrategy();        CloseableHttpClient httpclient = HttpClients.custom()                .setRedirectStrategy(redirectStrategy)                .build();        HttpClientContext context = HttpClientContext.create();        try {            // 以post方法执行登陆请求
            HttpPost httpPost = new HttpPost(urlString);            List<NameValuePair> nvps = new ArrayList<NameValuePair>();            nvps.add(new BasicNameValuePair("username", "admin"));            nvps.add(new BasicNameValuePair("password", "admin"));            // 添加post参数
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));            CloseableHttpResponse response = httpclient.execute(httpPost, context);            try {                // 状态302的话,重定向,则没法获取响应消息体                System.out.println(response.getStatusLine());                // 得到服务器响应的消息体(不包括http head)
                HttpEntity entity = response.getEntity();                //输出最终访问地址
                HttpHost targetHost = context.getTargetHost();                System.out.println(targetHost);                List<URI> redirecLocations = context.getRedirectLocations();                URI location = URIUtils.resolve(httpPost.getURI(), targetHost, redirecLocations);                System.out.println("Final HTTP location: " + location.toASCIIString());                                                if (entity != null) {                    // 得到响应字符集编码
                    ContentType contentType = ContentType.getOrDefault(entity);                    Charset charset = contentType.getCharset();                    InputStream is = entity.getContent();                    // 将inputstream转化为reader,并使用缓冲读取,还可按行读取内容
                    BufferedReader br = new BufferedReader(                            new InputStreamReader(is, charset));                    String line = null;                    while ((line = br.readLine()) != null) {                        System.out.println(line);                    }                    is.close();                }            } finally {                response.close();            }        } finally {            httpclient.close();        }
复制代码

4,利用httpclient,咱们能够封装一个方法,只要传入httpclient对象和url地址,便可返回网页内容。cookie

ExpandedBlockStart.gif
复制代码
publicstatic String getHtml(HttpClient httpClient, String url)  {        // HttpClient主要用来执行http方法
        CloseableHttpClient httpclient = HttpClients.createDefault();        try {            // 以get方法向服务端发起请求
            HttpGet httpGet = new HttpGet(url);            // 得到服务器响应的全部信息
            CloseableHttpResponse responseGet = httpclient.execute(httpGet);            try {                // 得到服务器响应的消息体(不包括http head)
                HttpEntity entity = responseGet.getEntity();                if (entity != null) {                    // 得到响应字符集编码
                    ContentType contentType = ContentType.getOrDefault(entity);                    Charset charset = contentType.getCharset();                    InputStream is = entity.getContent();                    //IOUtils是common-io提供的
                    String htmlString = IOUtils.toString(is);                                        is.close();                    return htmlString;                }            } finally {                responseGet.close();            }        } catch (Exception e) {            e.printStackTrace();        }                returnnull;    }
复制代码

  另外,若访问的是图片,则可从输入流中将内容存储到byte数组中,如byte[] p_w_picpath = IOUtils.toByteArray(is),返回byte[]便可;若想下载保存到本地,可以使用IOUtils的方法:IOUtils.copy(is, new FileOutputStream(filename))。ide

这里略提一下Apache-Commons-IO组件,它是对jdk中的io包进行拓展,让咱们能够更方便处理输入输出流和对文件的处理。工具

最后,要想学习熟悉httpclient,最好就是查看其官方文档和它提供的范例,它的文档和范例都很不错,推荐阅读。post



http://www.cnblogs.com/jianzhi/p/3362742.html

相关文章
相关标签/搜索