首页 > 应用开发 > Java > 构建Restful 的Java客户端
归纳来讲,构建Restful Web Sevice 客户端,需要三个主要的的步骤:
1,Come up你的数据,这些数据将用来形成最终的Http Request,
这些数据包括:Http方法,URI,Http Headers等。
2, 形成Http Request, send it to http server.
3,Parse返回的结果,形成你要的结果。
2,3步的实现需要类库的帮助。
对于第二步,一般有三种方法是实现:
->使用java.net package提供的Http Client功能。
不过使用这种方法,由于其提供的功能的有限性(如不支持cookies,不支持认证),编写Http Client比较困难。
-> 使用强大的Apache Jakarta HttpClient.以下是其支持的feature列表:
* Standards based, pure Java, implementation of HTTP versions 1.0 and 1.1
* Full implementation of all HTTP methods (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE) in an extensible OO framework.
* Supports encryption with HTTPS (HTTP over SSL) protocol.
* Granular non-standards configuration and tracking.
* Transparent connections through HTTP proxies.
* Tunneled HTTPS connections through HTTP proxies, via the CONNECT method.
* Transparent connections through SOCKS proxies (version 4 & 5) using native Java socket support.
* Authentication using Basic, Digest and the encrypting NTLM (NT Lan Manager) methods.
* Plug-in mechanism for custom authentication methods.
* Multi-Part form POST for uploading large files.
* Pluggable secure sockets implementations, making it easier to use third party solutions
* Connection management support for use in multi-threaded applications. Supports setting the maximum total connections as well as the maximum connections per host. Detects and closes stale connections.
* Automatic Cookie handling for reading Set-Cookie: headers from the server and sending them back out in a Cookie: header when appropriate.
* Plug-in mechanism for custom cookie policies.
* Request output streams to avoid buffering any content body by streaming directly to the socket to the server.
* Response input streams to efficiently read the response body by streaming directly from the socket to the server.
* Persistent connections using KeepAlive in HTTP/1.0 and persistance in HTTP/1.1
* Direct access to the response code and headers sent by the server.
* The ability to set connection timeouts.
* HttpMethods implement the Command Pattern to allow for parallel requests and efficient re-use of connections.
* Source code is freely available under the Apache Software License.
见:http://hc.apache.org/httpclient-3.x/.
->使用Restlet Http Client Lib.Restlet提供了两个HTTP客户端连接器(HTTP client connector)。它们一个是基于官方的HttpURLConnection类,
一个是基于Apache的HTTP客户端库。
见:http://www.restlet.org
对于第三步,当然使用名满天下的Xerces XML Parser.
Xerces来自IBM捐赠给Apache的XML4J项目
见:http://xerces.apache.org/xerces2-j/
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/17131144/viewspace-1015430/ ,如需转载,请注明出处,否则将追究法律责任。