友汇网网站建设管理后台网站,潍坊网站建设品牌,网站网站设计公司,职业学院网站建设方案最近#xff0c;我不得不编写一些Java代码以通过HTTP 使用 REST服务 。 我决定使用RestEasy的客户端库#xff0c;该框架是我大部分时间用来公开Java REST服务的框架#xff0c;因为它也实现了官方的JAX-RS规范。 我对规范定义的注释驱动方法非常满意#xff0c;这使REST服… 最近我不得不编写一些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接口。 所有这些TwitterGoogle或其他可用的公共休息服务都只有HTTP端点。 在这些情况下使用RestEasy的方法是依靠RestEasy手动ClientRequest API ClientRequest request new ClientRequest(http://localhost:8080/some/path);
request.header(custom-header, value);// Were posting XML and a JAXB object
request.body(application/xml, someJaxb);// were expecting a String back
ClientResponseString 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(); 返回 errorserror code34Sorry, that page does not exist/error
/errors 呃有些错误 。 是的我们需要传递一些参数 with().parameter(screen_name, resteasy)
.get(http://api.twitter.com/1/users/show.xml).asString(); 返回 userid27016395/idnameResteasy/namescreen_nameresteasy/screen_namelocation/locationprofile_image_urlhttp://a0.twimg.com/sticky/default_profile_images/default_profile_0_normal.png/profile_image_urlprofile_image_url_httpshttps://si0.twimg.com/sticky/default_profile_images/default_profile_0_normal.png/profile_image_url_httpsurl/urldescriptionjboss.org/resteasyJBoss/Red Hat REST project/descriptionprotectedfalse/protectedfollowers_count244/followers_countprofile_background_colorC0DEED/profile_background_colorprofile_text_color333333/profile_text_colorprofile_link_color0084B4/profile_link_colorprofile_sidebar_fill_colorDDEEF6/profile_sidebar_fill_colorprofile_sidebar_border_colorC0DEED/profile_sidebar_border_colorfriends_count1/friends_countcreated_atFri Mar 27 14:39:52 0000 2009/created_atfavourites_count0/favourites_countutc_offset/utc_offsettime_zone/time_zoneprofile_background_image_urlhttp://a0.twimg.com/images/themes/theme1/bg.png/profile_background_image_urlprofile_background_image_url_httpshttps://si0.twimg.com/images/themes/theme1/bg.png/profile_background_image_url_httpsprofile_background_tilefalse/profile_background_tileprofile_use_background_imagetrue/profile_use_background_imagegeo_enabledfalse/geo_enabledverifiedfalse/verifiedstatuses_count8/statuses_countlangen/langcontributors_enabledfalse/contributors_enabledis_translatorfalse/is_translatorlisted_count21/listed_countdefault_profiletrue/default_profiledefault_profile_imagetrue/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依赖项 dependencygroupidcom.jayway.restassured/groupidartifactidrest-assured/artifactidversion1.4/versionscopetest/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