Java:放心(或非常容易)

最近,我不得不编写一些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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/369515.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

php输出json到表格,PHP中把数据库查询结果输出为json格式

header("Content-type:text/html;charsetutf-8");//字符编码设置$servername "localhost";$username "root";$password "root";$dbname "tjks";// 创建连接$con mysqli_connect($servername, $username, $password, $db…

CSS中的overflow属性

overflow属性 如果元素中的内容超出了给定的宽度和高度属性&#xff0c;overflow 属性可以确定是否显示滚动条&#xff0c;是否隐藏溢出部分等行为&#xff0c;规定当内容溢出元素框时发生的事情。 可能的值有&#xff1a; visible&#xff1a;默认值。内容不会被修剪&#xff…

COGS 13. 运输问题4

★★☆ 输入文件&#xff1a;maxflowd.in 输出文件&#xff1a;maxflowd.out 简单对比时间限制&#xff1a;1 s 内存限制&#xff1a;128 MB 【问题描述】一个工厂每天生产若干商品&#xff0c;需运输到销售部门进行销售。从产地到销地要经过某些城镇&#xff0c;有不同…

Java –手工Classloader隔离

在最近的项目中&#xff0c;我们遇到了一个典型的库冲突问题 。 我们可以控制的一个组件需要特定版本的Apache Commons库&#xff0c;而另一个组件则需要一个不同的版本。 由于外部限制&#xff0c; 我们无法在Container级别指定任何类加载隔离 。 这不是我们的选择。 相反&…

【知识梳理1】Android触摸事件机制

前言 随着科学技术的发展&#xff0c;智能手机早已成为我们当代人身边不可缺少的“伙伴”之中的一个&#xff0c;堪比对象女友。每天我们对着手机反复的做着点击、滑动操作&#xff0c;而手机则随着我们的操作给我们展示她的精彩。… 废话到此结束。 看到这里&#xff0c;即使…

matlab if m不等于0,matlab问题clearfor a=0.1:0.1:50for b=0.1:0.1:20for m=0.1:0.1:5

来源&#xff1a;学生作业帮 编辑&#xff1a;作业帮 分类&#xff1a;综合作业 时间&#xff1a;2021/03/23 06:16:09matlab问题clearfor a0.1:0.1:50for b0.1:0.1:20for m0.1:0.1:5for k1:1:15n(a*m)/(2*b)-m^2;z4*k-a*m;x(4*k-a*m)/(4*k-2*b*(m^2n));y(4*k-a*m)/(4*k-2*b*m^…

自己做的一个登录页面,纯代码!

先上效果图吧. 本人菜鸟入门, 请勿喷. 首先样式: 1 1 body{2 2 margin: 0;3 3 padding: 0;4 4 width: 100%;5 5 height: 100%;6 6 }7 7 8 8 .headers{9 9 width: 100%;10 10 height: 100px;11 11 }12 12 .siv-ng{13 13 width:…

ASP.NET调用cmd命令提示符拒绝访问解决方案

using System.Diagnostics; public class CmdHelper{private static string CmdPath "C:\Windows\System32\cmd.exe";/// <summary>/// 执行cmd命令/// 多命令请使用批处理命令连接符&#xff1a;/// <![CDATA[/// &:同时执行两个命令/// |:将上一个命…

Java 7:Fork / Join框架示例

Java 7中的Fork / Join Framework专为可分解为较小任务的工作而设计&#xff0c;并将这些任务的结果组合起来以产生最终结果。 通常&#xff0c;使用Fork / Join Framework的类遵循以下简单算法&#xff1a; // pseudocode Result solve(Problem problem) {if (problem.size &…

php上传文件 服务器内部错误,php – 在将图像上传到S3时遇到内部服务器错误500...

在将图像上传到S3时我遇到了一个问题.我正在使用S3类和jqueryimageuploader插件.我已经设置了基本的应用程序,它在我的本地机器上运行良好.当我在beanstalk上部署它时,它开始抛出错误.我已经附加了控制台快照.我在这里添加我的代码供参考.这是启动文件index.html –gt;Meta cha…

Some reading, some thinking.

update&#xff1a;感谢助教0 0又学会一招&#xff0c;play 了一下CSS Part 1 Reading AuthorArticleNoteMadcola《两年波折路&#xff08;考研、工作、考研&#xff09;》"吾志所向&#xff0c;一往无前&#xff1b;愈挫愈奋&#xff0c;再接再励。"辜新星《时刻调…

CSS选择器:伪类(图文详解)

本文最初发表于博客园&#xff0c;并在GitHub上持续更新前端的系列文章。欢迎在GitHub上关注我&#xff0c;一起入门和进阶前端。 以下是正文。 伪类&#xff08;伪类选择器&#xff09; 伪类&#xff1a;同一个标签&#xff0c;根据其不同的种状态&#xff0c;有不同的样式。…

了解播放过滤器API

随着Play 2.1的热销&#xff0c;很多人开始询问新的Play过滤器API。 实际上&#xff0c;API非常简单&#xff1a; trait EssentialFilter {def apply(next: EssentialAction): EssentialAction }本质上&#xff0c;过滤器只是一个执行一个动作并返回另一个动作的函数。 过滤器…

mybatis 使用merge into

前一篇博客&#xff0c;oracle的merge into语法 &#xff1a; oracle merge into语法 mybatis 使用merge into&#xff0c;跟一般的update写法相同&#xff1a; <update id"mergeinfo">merge into user_type ausing ( select #{name} as name, #{type} as type…

php getbyid,ThinkPHP查询中的魔术方法简述

我们在使用thinkphp开发的时候&#xff0c;有时候会用到getById(1)这个方法快速的获取一条信息的内容&#xff0c;这个方法比用where(" id 1 ")->find()好用多了&#xff0c;同时查询效率也比find快速。很多人在刚开始接触这个方法的时候&#xff0c;没有多留意它…

DIV固定宽度和动态拉伸混合水平排列

1.效果图 2.源代码 html <h2>1.头部固定&#xff0c;尾部拉伸</h2> <div class"container" id"div1"><div class"head"></div><div class"tail"></div> </div><h2>2.尾部固定…

bzoj1941 [Sdoi2010]Hide and Seek

Description 小猪iPig在PKU刚上完了无聊的猪性代数课&#xff0c;天资聪慧的iPig被这门对他来说无比简单的课弄得非常寂寞&#xff0c;为了消除寂寞感&#xff0c;他决定和他的好朋友giPi&#xff08;鸡皮&#xff09;玩一个更加寂寞的游戏—捉迷藏。 但是&#xff0c;他们觉得…

ubuntu修改ssh服务的端口号

一、找到ssh配置文件位置 vim /etc/ssh/sshd_config 二、修改ssh登录端口号 修改 port 22 为 port xxxx 三、重启ssh服务 /etc/init.d/ssh restart转载于:https://www.cnblogs.com/javafucker/p/8521316.html

使用CSS设置JavaFX饼图样式

渲染图表时&#xff0c; JavaFX默认提供某些颜色。 但是&#xff0c;在某些情况下&#xff0c;您想自定义这些颜色。 在此博客文章中&#xff0c;我将使用一个示例来更改JavaFX饼图的颜色&#xff0c;该示例打算在今天下午在RMOUG Training Days 2013的演示中包括。一些基于Jav…

python列表去重效率,你应该知道的python列表去重方法

前言列表去重是写Python脚本时常遇问题&#xff0c;因为不管源数据来自哪里&#xff0c;当我们转换成列表的方式时&#xff0c;有可能预期的结果不是我们最终的结果&#xff0c;最常见的就是列表中元素有重复&#xff0c;这时候第一件事我们就要做去重处理。我们先来个最简单的…