HttpClient 4.3教程 第一章 基本概念

第一章 基本概念

1.1. 请求执行

HttpClient最基本的功能就是执行Http方法。一个Http方法的执行涉及到一个或者多个Http请求/Http响应的交互,一般这个过程都会自动被HttpClient处理,对用户透明。用户只须要提供Http请求对象,HttpClient就会将http请求发送给目标服务器,而且接收服务器的响应,若是http请求执行不成功,httpclient就会抛出异样。 下面是个很简单的http请求执行的例子:
CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet("http://www.yeetrack.com/");
    CloseableHttpResponse response = httpclient.execute(httpget);
    try {
        <...>
    } finally {
        response.close();
    }

1.1.1. Http请求

全部的Http请求都有一个请求列(request line),包括方法名、请求的URI和Http版本号。 HttpClient支持HTTP/1.1这个版本定义的全部Http方法:GET,HEAD,POST,PUT,DELETE,'TRACE和OPTIONS。对于每一种http方法,HttpClient都定义了一个相应的类:HttpGet,HttpHead,HttpPost,HttpPut,HttpDelete,HttpTrace和HttpOpquertions`。 Request-URI即统一资源定位符,用来标明Http请求中的资源。Http request URIS包含协议名、主机名、主机端口(可选)、资源路径、query(可选)和片断信息(可选)。
HttpGet httpget = new HttpGet(
 "http://www.google.com/search?hl=en&q=httpclient&btnG=Google+Search&aq=f&oq=");
HttpClient提供URIBuilder工具类来简化URIs的建立和修改过程。
URI uri = new URIBuilder()
    .setScheme("http")
    .setHost("www.google.com")
    .setPath("/search")
    .setParameter("q", "httpclient")
    .setParameter("btnG", "Google Search")
    .setParameter("aq", "f")
    .setParameter("oq", "")
    .build();
    HttpGet httpget = new HttpGet(uri);
    System.out.println(httpget.getURI());

上述代码会在控制台输出: 服务器


继续阅读→

相关文章
相关标签/搜索