10
HttpClient
Calvin Xiao edited this page 2014-01-26 19:45:53 -08:00
This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

##1. Overview HttpClient有两种选择

  1. JDK自带的HttpURLConnection 或 Apache HttpClient
  2. Jersey/CXF的Restful Client和 Spring的RestTemplate。

对于很Restful的服务端Jersey/CXF/Spring的Restful Client能更好的打交道比如发送和读取Restful应用常用的参数转换json格式的数据等等。

如果是简单Http请求不考虑性能可以直接使用HttpURLConnection 够简单不需要引入额外依赖包。但HttpURLConnection控制Keep-Alive长连接不方便(见后),还有其他进一步的需求时比如设定最大连接池,Cookies与认证的功能更强等等换用Apache HttpClient。

##2. Apache Http Client 在showcase的RemoteContentServlet, 演示了多线程安全的使用了ConnectionPool的Apache HttpClient, 并演示了如何设置SocketTimeout。

2.1 HttpClient4.3 Fluent API

HttpClient原来的API非常复杂而且还要记着关闭InputStreamHttp4.3终于提供了Fluent API, 同样在showcase的RemoteContentServlet中演示。

Request.Get(url).execute().returnContent().asString();

通过翻代码可以看到它线程安全所有请求会使用一个公共的连接池总共200连接每个destination最多100个连接。而且内容会立刻全部读出然后关闭inputsream不需要再用代码去关闭。

如果你想设置自己的连接池或者设置超时则需要先设置好httpClient然后传入。

Executor executor = Executor.newInstance(httpClient);
String resultString = executor.execute(Request.Get(url)).returnContent().asString();

##3. JDK HttpConnectionURL 同样在showcase的RemoteContentServlet中演示。

缺陷是长连接只能JVM全局统一配置 系统变量 http.keepAlive默认为truehttp.maxConnections默认为5是每个destination 的最大连接数。

##Spring RestTemplate/Jersey Client 简单情形下直接用Spring自带RestTemplate即可Spring Restful章节。 当觉得不够用时可尝试使用Jersey Client Jersey也是Jax-RS2.0规范对于Client端的参考实现不过好久没用过Jersey了。