zoukankan      html  css  js  c++  java
  • Part2-HttpClient官方教程-Chapter5-流利的API

    5.1. 易于使用的Facade API

    使用之前注意引入相应Jar包或者Maven依赖

    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>fluent-hc</artifactId>
      <version>4.5.5</version>
    </dependency>

    从4.2版开始,HttpClient基于流畅的界面概念提供了一个易于使用的Facade API。 Fluent Facade API只公开了HttpClient的最基本的功能,并且适用于不需要HttpClient的全部灵活性的简单用例。 例如,流畅的Facade API可以让用户不必处理连接管理和资源释放。
    以下是通过HC fluent API执行的HTTP请求的几个示例

    // 使用超时设置执行GET请求并将响应内容作为字符串返回。
    //html包含百度首页的源代码,可能会出现乱码问题,设置编码格式即可。
    String html = Request.Get("https://www.baidu.com/").connectTimeout(1000).socketTimeout(1000).execute()
                    .returnContent().asString();
    // 通过包含请求主体的代理执行带自定义标题的POST请求
    // 作为HTML表单并将结果保存到文件中
    Request.Post("http://somehost/some-form")
            .addHeader("X-Custom-header", "stuff")
            .viaProxy(new HttpHost("myproxy", 8080))
            .bodyForm(Form.form().add("username", "vip").add("password", "secret").build())
            .execute().saveContent(new File("result.dump"));
    

    也可以直接使用Executor来执行特定安全上下文中的请求,从而将身份验证细节缓存起来并重新用于后续请求。

    Executor executor = Executor.newInstance()
            .auth(new HttpHost("somehost"), "username", "password")
            .auth(new HttpHost("myproxy", 8080), "username", "password")
            .authPreemptive(new HttpHost("myproxy", 8080));
    
    executor.execute(Request.Get("http://somehost/"))
            .returnContent().asString();
    
    executor.execute(Request.Post("http://somehost/do-stuff")
            .useExpectContinue()
            .bodyString("Important stuff", ContentType.DEFAULT_TEXT))
            .returnContent().asString();

    5.1.1. 响应处理

    流畅的Facade API通常使用户不必处理连接管理和资源释放。 但是在大多数情况下,这是以不得不缓冲内存中响应消息的内容为代价的。 强烈建议使用ResponseHandler进行HTTP响应处理,以避免在内存中缓冲内容。

    Document result = Request.Get("http://somehost/content")
            .execute().handleResponse(new ResponseHandler<Document>() {
    
        public Document handleResponse(final HttpResponse response) throws IOException {
            StatusLine statusLine = response.getStatusLine();
            HttpEntity entity = response.getEntity();
            if (statusLine.getStatusCode() >= 300) {
                throw new HttpResponseException(
                        statusLine.getStatusCode(),
                        statusLine.getReasonPhrase());
            }
            if (entity == null) {
                throw new ClientProtocolException("Response contains no content");
            }
            DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
            try {
                DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
                ContentType contentType = ContentType.getOrDefault(entity);
                if (!contentType.equals(ContentType.APPLICATION_XML)) {
                    throw new ClientProtocolException("Unexpected content type:" +
                        contentType);
                }
                String charset = contentType.getCharset();
                if (charset == null) {
                    charset = HTTP.DEFAULT_CONTENT_CHARSET;
                }
                return docBuilder.parse(entity.getContent(), charset);
            } catch (ParserConfigurationException ex) {
                throw new IllegalStateException(ex);
            } catch (SAXException ex) {
                throw new ClientProtocolException("Malformed XML document", ex);
            }
        }
    
        });
    
  • 相关阅读:
    zookeeper3.5.6单机集群环境搭建
    mycat分表
    myacat分片及全局表定义
    装饰器
    函数参数,作用域
    可变,不可变,无序, 有序
    dict
    列表可变,元祖不可变
    列表操作
    字符串find
  • 原文地址:https://www.cnblogs.com/snailclimb/p/9086446.html
Copyright © 2011-2022 走看看