首页 > 其他 > 详细

利用HttpClient4进行网络通讯

时间:2014-03-16 18:42:54      阅读:458      评论:0      收藏:0      [点我收藏+]

一、HttpClient介绍

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

二、使用范例 (以下版本4.3)

1 ,通过get方式,请求网页内容。我们首先创建httpclient对象,然后通过httpclient来执行http get方法,httpresponse获得服务端响应的所有内容,httpentity为获取的网页消息体。

bubuko.com,布布扣
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();
        }
bubuko.com,布布扣

 

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

bubuko.com,布布扣
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();
            }
bubuko.com,布布扣

 

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

bubuko.com,布布扣
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();
        }
bubuko.com,布布扣

利用HttpClient4进行网络通讯,布布扣,bubuko.com

利用HttpClient4进行网络通讯

原文:http://www.cnblogs.com/updateofsimon/p/3603484.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!