httpclient 4.5.2 学习随笔(2)

作者: 起个名忒难 | 来源:发表于2016-12-05 22:56 被阅读294次

    HTML表单

    许多应用需要模仿一个登陆HTML表单的过程,比如:为了登陆一个WEB应用或者提交输入的数据。Httpclient 早就为我们准备好了,提供了UrlEncodedFormEntity类来简化操作。
    我们来看一下核心的代码:

    List<NameValuePair> list = new ArrayList<>() ;
    list.add(new BasicNameValuePair("name" ,"zhangsan"));
    list.add(new BasicNameValuePair("age" ,"18"));
    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list ,Consts.UTF_8) ;
    

    post方法提交demo

    import org.apache.http.Consts;
    import org.apache.http.HttpStatus;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * Created by YuLuo on 2016/12/5.
     */
    public class PostDemo {
        public static void main(String[] args) throws IOException {
            demo();
        }
        public static void demo() throws IOException {
            //创建httpclient 实例
            CloseableHttpClient httpclient = HttpClients.createDefault();
            //创建post方法实例
            HttpPost post = new HttpPost("http://host/.com") ;
    
            //封装提交到服务器的参数信息
            List<NameValuePair> list = new ArrayList<>() ;
            list.add(new BasicNameValuePair("name" ,"zhangsan"));
            list.add(new BasicNameValuePair("age" ,"18"));
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list , Consts.UTF_8) ;
            //设置参数信息
            post.setEntity(formEntity);
            //提交post方法
            CloseableHttpResponse respone = httpclient.execute(post);
    
            int statcode = respone.getStatusLine().getStatusCode() ;
            if(statcode == HttpStatus.SC_OK){
                System.out.println(EntityUtils.toString(respone.getEntity()));
            }
        }
    
    }
    

    **解析NameValuePair **
    通过查看源码,发现NameValuePair只有两个方法:

    1. getName()
    2. getValue()

    BasicNameValuePair作为NameValuePair的实现类,只有两个字段,Name和Value ,并且它还实现了Cloneable ,Serializable 两个接口。BasicNameValuePair 没有提供属性的setter方法。只能通过构造方法,为字段赋值。

    内容分块

    通过HTTP#setChunded()方法来通知HttpClient你要进行分块处理, 由Httpclient根据被传输的报文属性选择最合适的传输编码方式。当使用一些不支持分块的版本(http /1.0)时,这个值会被忽略掉。

    Http执行上下文 context

    最初,HTTP是被设计成无状态的,面向请求-响应协议。然而,我们在使用的过程中,经常需要一些逻辑相关的请求-响应交换来保持状态信息。为了使应用程序能够维持一个过程状态,httpclient允许HTTP请求在一个特定的执行上下文中来执行--称为HTTP上下文。

    HttpContext能够包含任意的对象,因此在两个不同的线程中共享上下文是不安全的。建议每个线程都有一个自己的上下文。

    在HTTP请求执行的过程中,HttpClient添加了下列属性到执行上下文中:

    • HttpConnection 实例代表连接到目标服务器的当前连接
    • HttpHost 实例代表连接到目标服务器的当前连接
    • HttpRoute 实例代表了完整的连接路由
    • HttpRequest 实例代表了当前的HTTP请求。
    • HttpResponse 实例代表了当前的HTTP响应。
    • RequestConfig 代表当前请求配置。
    • java.util.List<URI> 对象代表一个含有执行请求过程中所有重定向的地址。

    小demo
    请求配置在最初被初始化,它将在执行上下文中一直保持,共享同一个会话的所有连续请求

     public static void contextDemo() throws IOException {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            RequestConfig config = RequestConfig
                                            .custom()
                                            .setConnectionRequestTimeout(3000)
                                            .setConnectTimeout(3000)
                                            .setSocketTimeout(3000)
                                            .build();
            HttpGet get = new HttpGet("http://www.baidu.com");
            get.setConfig(config);
            HttpClientContext context = HttpClientContext.create();
            CloseableHttpResponse response = httpclient.execute(get, context);
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("---------------------------------");
            HttpGet get1 = new HttpGet("http://www.qq.com");
            get1.setConfig(config);
            CloseableHttpResponse res = httpclient.execute(get1, context);
            System.out.println(EntityUtils.toString(res.getEntity()));
        }
    

    异常处理
    HttpClient 能够抛出两种类型的异常:

    1. java.io.IOException ,如socket 连接超时或被重置的异常。
    2. HttpException :标志Http请求失败的信号,如违反HTTP协议。

    I/O 错误被认为是非致命的和可以恢复的,而HTTP协议错误,则被认为是致命的而且是不能自动恢复的。

    请求尝试处理器

    为了能使用自定义异常的回复机制,必须要实现HttpRequestRetryHandler接口。

    小demo

    public static void requestRetryDemo() throws IOException {
            CloseableHttpClient httpClient = HttpClients
                    .custom()
                    .setRetryHandler(DefaultHttpRequestRetryHandler.INSTANCE)
                    .build();
            HttpGet get = new HttpGet("http://www.baidu.com") ;
            CloseableHttpResponse response = httpClient.execute(get);
            System.out.println(EntityUtils.toString(response.getEntity()));
        }
    

    上例中我们使用了默认的请求重试类,默认重试次数为三次,requestSentRetryEnabled 为false,当然我们也可以自己定制,具体的参数请自行查阅源码

    请求终止

    使用HttpRequest#abort()来终止线程 ;该方法为线程安全的,可以从任意线程调用。

    重定向处理

    重定向的url,通过HttpContext#getRedirectLocation().获取重定向网址。

    参考: http://blog.csdn.net/u011179993/article/details/47123727


    少年听雨歌楼上,红烛昏罗帐。  
    壮年听雨客舟中,江阔云低,断雁叫西风。
    感谢支持!
                                            ---起个名忒难
    

    相关文章

      网友评论

        本文标题:httpclient 4.5.2 学习随笔(2)

        本文链接:https://www.haomeiwen.com/subject/neplmttx.html