最近,我不得不编写一些Java代码以通过HTTP 使用 REST服务 。 我决定使用RestEasy的客户端库,该框架是我大部分时间用来公开Java REST服务的框架,因为它也实现了官方的JAX-RS规范。 我对规范定义的注释驱动方法非常满意,这使REST服务公开成为一项非常愉快的任务。 但不幸的是, 我不能说我以同样的方式喜欢客户端API 。 如果您有幸能够根据服务实现的接口构建代理客户端,那还不错:
import org.jboss.resteasy.client.ProxyFactory;
...
// this initialization only needs to be done once per VM
RegisterBuiltin.register(ResteasyProviderFactory.getInstance());SimpleClient client = ProxyFactory.create(MyRestServiceInterface.class, 'http://localhost:8081');
client.myBusinessMethod('hello world');
我同意拥有一个类似于JAX-WS的代理客户端是很好的。 但是大多数时候,当我们使用REST Web服务时,我们没有要导入的Java接口。 所有这些Twitter,Google或其他可用的公共休息服务都只有HTTP端点。 在这些情况下,使用RestEasy的方法是依靠RestEasy手动ClientRequest API:
ClientRequest request = new ClientRequest('http://localhost:8080/some/path');
request.header('custom-header', 'value');// We're posting XML and a JAXB object
request.body('application/xml', someJaxb);// we're expecting a String back
ClientResponse<String> response = request.post(String.class);if (response.getStatus() == 200) // OK!
{String str = response.getEntity();
}
我认为这是一种非常冗长的方式来获取大多数时间的内容,只需从网络中获取一串字符串即可。 如果需要包括身份验证信息,情况将变得更加糟糕:
// Configure HttpClient to authenticate preemptively
// by prepopulating the authentication data cache.// 1. Create AuthCache instance
AuthCache authCache = new BasicAuthCache();// 2. Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put('com.bluemonkeydiamond.sippycups', basicAuth);// 3. Add AuthCache to the execution context
BasicHttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);// 4. Create client executor and proxy
httpClient = new DefaultHttpClient();
ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient, localContext);
client = ProxyFactory.create(BookStoreService.class, url, executor);
我发现Rest-assured提供了一个更好的API来编写客户端调用。 该项目的正式目的是建立一个测试和验证框架 ; 而且大多数教程都涵盖了这些方面,例如最近的Heiko Rupp的教程: http : //pilhuhn.blogspot.nl/2013/01/testing-rest-apis-with-rest-assured.html 。 我建议您改为使用它作为开发工具来非常快速地进行实验和编写REST调用。 关于放心的重要事项:
- 它通过流畅的API实现了特定于域的语言
- 它是单个Maven依赖项
- 它几乎完全公开了xml和json响应对象的共享样式
- 它依赖于Apache Commons Client
因此,我将向您展示大量实际的用例,如果您想了解更多信息,我将为您提供一些良好的链接。 与Java上的大多数DSL一样,如果您静态导入最重要的对象 ,效果会更好:
import static com.jayway.restassured.RestAssured.*;
import static com.jayway.restassured.matcher.RestAssuredMatchers.*;
基本用法:
get('http://api.twitter.com/1/users/show.xml').asString();
返回:
<errors><error code="34">Sorry, that page does not exist</error>
</errors>
呃,有些错误 。 是的,我们需要传递一些参数:
with().parameter('screen_name', 'resteasy')
.get('http://api.twitter.com/1/users/show.xml').asString();
返回:
<user><id>27016395</id><name>Resteasy</name><screen_name>resteasy</screen_name><location></location><profile_image_url>http://a0.twimg.com/sticky/default_profile_images/default_profile_0_normal.png</profile_image_url><profile_image_url_https>https://si0.twimg.com/sticky/default_profile_images/default_profile_0_normal.png</profile_image_url_https><url></url><description>jboss.org/resteasyJBoss/Red Hat REST project</description><protected>false</protected><followers_count>244</followers_count><profile_background_color>C0DEED</profile_background_color><profile_text_color>333333</profile_text_color><profile_link_color>0084B4</profile_link_color><profile_sidebar_fill_color>DDEEF6</profile_sidebar_fill_color><profile_sidebar_border_color>C0DEED</profile_sidebar_border_color><friends_count>1</friends_count><created_at>Fri Mar 27 14:39:52 +0000 2009</created_at><favourites_count>0</favourites_count><utc_offset></utc_offset><time_zone></time_zone><profile_background_image_url>http://a0.twimg.com/images/themes/theme1/bg.png</profile_background_image_url><profile_background_image_url_https>https://si0.twimg.com/images/themes/theme1/bg.png</profile_background_image_url_https><profile_background_tile>false</profile_background_tile><profile_use_background_image>true</profile_use_background_image><geo_enabled>false</geo_enabled><verified>false</verified><statuses_count>8</statuses_count><lang>en</lang><contributors_enabled>false</contributors_enabled><is_translator>false</is_translator><listed_count>21</listed_count><default_profile>true</default_profile><default_profile_image>true</default_profile_image>
...
</user>
好多了! 现在,假设我们只想要这个大String XML的令牌 :
with().parameter('screen_name', 'resteasy')
.get('http://api.twitter.com/1/users/show.xml').path('user.profile_image_url')
这是我们的输出:
http://a0.twimg.com/sticky/default_profile_images/default_profile_0_normal.png
如果是JSON响应怎么办?
with().parameter('screen_name', 'resteasy')
.get('http://api.twitter.com/1/users/show.json')
这是我们的输出:
{"id":27016395,"id_str":"27016395","name":"Resteasy","screen_name":"resteasy","location":"","url":null,"description":"jboss.org\/resteasy\n\nJBoss\/Red Hat REST project","protected":false,"followers_count":244,"friends_count":1,"listed_count":21,"created_at":"Fri Mar 27 14:39:52 +0000 2009","favourites_count":0,"utc_offset":null,"time_zone":null,"geo_enabled":false,"verified":false,"statuses_count":8,"lang":"en","status":{"created_at":"Tue Mar 23 14:48:51 +0000 2010","id":10928528312,"id_str":"10928528312","text":"Doing free webinar tomorrow on REST, JAX-RS, RESTEasy, and REST-*. Only 40 min, so its brief. http:\/\/tinyurl.com\/yz6xwek","source":"web","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"geo":null,"coordinates":null,"place":null,"contributors":null,"retweet_count":0,"favorited":false,"retweeted":false},"contributors_enabled":false,"is_translator":false,"profile_background_color":"C0DEED","profile_background_image_url":"http:\/\/a0.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/si0.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_image_url":"http:\/\/a0.twimg.com\/sticky\/default_profile_images\/default_profile_0_normal.png","profile_image_url_https":"https:\/\/si0.twimg.com\/sticky\/default_profile_images\/default_profile_0_normal.png","profile_link_color":"0084B4","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"default_profile":true,"default_profile_image":true,"following":null,"follow_request_sent":null,"notifications":null}
并且同一接口无法理解JSON对象导航。 请注意,导航表达式不包含“用户”,因为它在完整的json响应中不存在:
with().parameter('screen_name', 'resteasy')
.get('http://api.twitter.com/1/users/show.json').path('profile_image_url')
这是我们的输出:
http://a0.twimg.com/sticky/default_profile_images/default_profile_0_normal.png
现在是路径参数的示例:
with().parameter('key', 'HomoSapiens')
.get('http://eol.org/api/search/{key}').asString()
有关http请求的信息 :
get('http://api.twitter.com/1/users/show.xml').statusCode();
get('http://api.twitter.com/1/users/show.xml').statusLine();
基本身份验证的示例:
with().auth().basic('paolo', 'xxxx')
.get('http://localhost:8080/b/secured/hello').statusLine()
分段表格上传的示例
with().multiPart('file', 'test.txt', fileContent.getBytes())
.post('/upload')
Maven依赖项 :
<dependency><groupid>com.jayway.restassured</groupid><artifactid>rest-assured</artifactid><version>1.4</version><scope>test</scope>
</dependency>
得益于Grapes ,可以在groovyConsole中直接粘贴和执行的Groovy代码片段提取依赖关系并将其自动添加到类路径中,从而向您展示JAXB支持:
@Grapes([ @Grab('com.jayway.restassured:rest-assured:1.7.2')
])
import static com.jayway.restassured.RestAssured.*
import static com.jayway.restassured.matcher.RestAssuredMatchers.*
import javax.xml.bind.annotation.*@XmlRootElement(name = 'user')
@XmlAccessorType( XmlAccessType.FIELD )class TwitterUser {String id;String name;String description;String location;@OverrideString toString() {return 'Id: $id, Name: $name, Description: $description, Location: $location'}}println with().parameter('screen_name', 'resteasy').get('http://api.twitter.com/1/users/show.xml').as(TwitterUser.class)//
这只是库功能的简短列表,只是您了解使用它的难易程度。 有关其他示例,建议您在此处阅读官方页面: https : //code.google.com/p/rest-assured/wiki/Usage 。 或此处提供的另一个具有示例应用程序的优秀教程: http : //www.hascode.com/2011/10/testing-restful-web-services-made-easy-using-the-rest-assured-framework
参考: Java:在Someday Never Comes博客上,由我们的JCG合作伙伴 Paolo Antinori 保证(或称Rest-Very-Easy) 。
翻译自: https://www.javacodegeeks.com/2013/03/java-rest-assured-or-rest-very-easy.html