类似于HttpClient的Java类库 - HTTPBuilder

fmms 12年前
     <p>如果熟悉HttpClient,那么你对 HTTPBuilder就不会感到陌生,它是对前者的封装,使之更符合Groovy的使用惯例。下面的例子摘自HTTPBuilder的文档,它充分展示 了自己的特点:</p>    <ul>     <li>Builder and parser support for <a href="/misc/goto?guid=4959517485830758671">XML</a>, <a href="/misc/goto?guid=4959517485910744344">JSON</a>, and HTML</li>     <li>Easy <a href="/misc/goto?guid=4959517485995192352">URI manipulation</a></li>     <li>Streamlined <a href="/misc/goto?guid=4959517486084220741">client for REST</a> interfaces</li>     <li>Built-in support for GZIP and Deflate content-encoding</li>     <li>Built-in support for most <a href="/misc/goto?guid=4959517486168474290">common authentication schemes</a></li>     <li>Status code based <a href="/misc/goto?guid=4959517486242213503">response handling</a></li>     <li>Convenience methods for <a href="/misc/goto?guid=4959517486321521417">GET</a> and <a href="/misc/goto?guid=4959517486398590483">POST</a></li>     <li><a href="/misc/goto?guid=4959517486483509595">Compatible</a> with Google App Engine</li>     <li><a href="/misc/goto?guid=4959517486568897648">AsyncHTTPBuilder</a> for asynchronous requests</li>     <li>Easily extensible API</li>    </ul>    <pre>import groovyx.net.http.HTTPBuilder import static groovyx.net.http.Method.GET import static groovyx.net.http.ContentType.TEXT   def http = new HTTPBuilder( 'http://www.google.com/search' )   http.request(GET,TEXT) { req ->   uri.path = '/mail/help/tasks/'   headers.'User-Agent' = 'Mozilla/5.0'      //请求成功   response.success = { resp, reader ->     assert resp.statusLine.statusCode == 200     println "My response handler got response: ${resp.statusLine}"     println "Response length: ${resp.headers.'Content-Length'}"     System.out << reader // print response stream   }    //404   response.'404' = { resp ->       println 'Not found'   }      // 401   http.handler.'401' = { resp ->     println "Access denied"   }    //其他错误,不实现则采用缺省的:抛出异常。   http.handler.failure = { resp ->     println "Unexpected failure: ${resp.statusLine}"   } }</pre>    <p>无需过多的讲解,上述的例子已经非常明白地说明了HTTPBuilder的基本使用。尽管如此,对于上例中的内容类型(即request括号中的 TEXT),还是有必要啰嗦几句。HTTPBuilder支持对响应内容的自动解析,解析的方式可在请求中指定,缺省除了TEXT之外,还支持XML、 HTML和JSON。如果在请求中不指定解析方式,那么它会根据响应的内容类型选择最合适的方式进行解析。对于每一种内容类型:</p>    <ul>     <li>TEXT,纯文本</li>     <li>XML,采用XmlSlurper解析内容</li>     <li>HTML,先采用NekoHTML使HTML 规范化,之后采用XmlSlurper解析DOM</li>     <li>JSON,采用JSON-lib解析内容</li>    </ul>    <p><strong>项目主页:</strong><a href="http://www.open-open.com/lib/view/home/1326987740249" target="_blank">http://www.open-open.com/lib/view/home/1326987740249</a></p>