日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > java >内容正文

java

Java:放心(或非常容易)

發(fā)布時間:2023/12/3 java 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java:放心(或非常容易) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

最近,我不得不編寫一些Java代碼以通過HTTP 使用 REST服務(wù) 。 我決定使用RestEasy的客戶端庫,該框架是我大部分時間用來公開Java REST服務(wù)的框架,因為它也實現(xiàn)了官方的JAX-RS規(guī)范。 我對規(guī)范定義的注釋驅(qū)動方法非常滿意,這使REST服務(wù)公開成為一項非常愉快的任務(wù)。 但不幸的是, 我不能說我以同樣的方式喜歡客戶端API 。 如果您有幸能夠根據(jù)服務(wù)實現(xiàn)的接口構(gòu)建代理客戶端,那還不錯:

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的代理客戶端是很好的。 但是大多數(shù)時候,當(dāng)我們使用REST Web服務(wù)時,我們沒有要導(dǎo)入的Java接口。 所有這些Twitter,Google或其他可用的公共休息服務(wù)都只有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(); }

我認(rèn)為這是一種非常冗長的方式來獲取大多數(shù)時間的內(nèi)容,只需從網(wǎng)絡(luò)中獲取一串字符串即可。 如果需要包括身份驗證信息,情況將變得更加糟糕:

// 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);

我發(fā)現(xiàn)Rest-assured提供了一個更好的API來編寫客戶端調(diào)用。 該項目的正式目的是建立一個測試和驗證框架 ; 而且大多數(shù)教程都涵蓋了這些方面,例如最近的Heiko Rupp的教程: http : //pilhuhn.blogspot.nl/2013/01/testing-rest-apis-with-rest-assured.html 。 我建議您改為使用它作為開發(fā)工具來非常快速地進行實驗和編寫REST調(diào)用。 關(guān)于放心的重要事項:

  • 它通過流暢的API實現(xiàn)了特定于域的語言
  • 它是單個Maven依賴項
  • 它幾乎完全公開了xml和json響應(yīng)對象的共享樣式
  • 它依賴于Apache Commons Client

因此,我將向您展示大量實際的用例,如果您想了解更多信息,我將為您提供一些良好的鏈接。 與Java上的大多數(shù)DSL一樣,如果您靜態(tài)導(dǎo)入最重要的對象 ,效果會更好:

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>

呃,有些錯誤 。 是的,我們需要傳遞一些參數(shù):

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>

好多了! 現(xiàn)在,假設(shè)我們只想要這個大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響應(yīng)怎么辦?

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對象導(dǎo)航。 請注意,導(dǎo)航表達式不包含“用戶”,因為它在完整的json響應(yīng)中不存在:

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

現(xiàn)在是路徑參數(shù)的示例:

with().parameter('key', 'HomoSapiens') .get('http://eol.org/api/search/{key}').asString()

有關(guān)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中直接粘貼和執(zhí)行的Groovy代碼片段提取依賴關(guān)系并將其自動添加到類路徑中,從而向您展示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)//

這只是庫功能的簡短列表,只是您了解使用它的難易程度。 有關(guān)其他示例,建議您在此處閱讀官方頁面: https : //code.google.com/p/rest-assured/wiki/Usage 。 或此處提供的另一個具有示例應(yīng)用程序的優(yōu)秀教程: 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

總結(jié)

以上是生活随笔為你收集整理的Java:放心(或非常容易)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。