javascript
stackexchange_通过Spring Social推特StackExchange –第1部分
stackexchange
 本文將介紹一個快速的附帶項目-一個自動從各種Q&A StackExchange網站上發布熱門問題的機器人,例如StackOverflow , ServerFault , SuperUser等。我們將為StackExchange API構建一個簡單的客戶端,然后進行設置使用Spring Social與Twitter API的交互-這第一部分將僅關注StackExchange Client。 此實現的最初目的不是要成為整個StackExchange API的完整客戶端-這不在本項目的范圍之內。 客戶端存在的唯一原因是,我無法對與正式API的2.x版本兼容的客戶端進行罰款。 
1. Maven依賴
要使用StackExchange REST API,我們將需要很少的依賴項-本質上只是一個HTTP客戶端-Apache HttpClient可以很好地滿足此目的:
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.2.3</version> </dependency還可以使用Spring RestTemplate與HTTP API進行交互,但這會在項目中引入很多其他與Spring相關的依賴項,這些依賴項不是嚴格必需的,因此HttpClient可以使事情變得簡單明了。
2.問題客戶
此客戶端的目標是使用StackExchange 發布的/ questions REST服務,而不是為整個StackExchange API提供通用客戶端–因此,出于本文的目的,我們將僅對此進行討論。 使用HTTPClient的實際HTTP通信相對簡單:
public String questions(int min, String questionsUri) {HttpGet request = null;try {request = new HttpGet(questionsUri);HttpResponse httpResponse = client.execute(request);InputStream entityContentStream = httpResponse.getEntity().getContent();return IOUtils.toString(entityContentStream, Charset.forName('utf-8'));} catch (IOException ex) {throw new IllegalStateException(ex);} finally {if (request != null) {request.releaseConnection();}} }這種簡單的交互非常適合獲取API發布的原始JSON問題–下一步將處理該JSON。 這里有一個相關的細節-也就是questionsUri方法參數 -有多個可以發布問題的StackExchange API(如官方文檔所建議的那樣),并且此方法必須足夠靈活才能使用所有問題。 例如,它可以使用最簡單的API(通過將questionUri設置為https://api.stackexchange.com/2.1/questions?site=stackoverflow來返回問題),也可以使用基于https://api.stackexchange.com/的標記取而代之的是2.1 / tags / {tags} / faq?site = stackoverflow API,具體取決于客戶端的需求。
對StackExchange API的請求已完全配置有查詢參數,即使對于更復雜的高級搜索查詢也是如此-沒有任何正文被發送。 為了構造questionsUri ,我們將構建一個基本的流暢的RequestBuilder類,該類將使用 HttpClient庫中的URIBuilder 。 這將確保正確編碼URI,并通常確保最終結果有效:
public class RequestBuilder {private Map<String, Object> parameters = new HashMap<>();public RequestBuilder add(String paramName, Object paramValue) {this.parameters.put(paramName, paramValue);return this;}public String build() {URIBuilder uriBuilder = new URIBuilder();for (Entry<String, Object> param : this.parameters.entrySet()) {uriBuilder.addParameter(param.getKey(), param.getValue().toString());}return uriBuilder.toString();} }因此,現在,為StackExchange API構造一個有效的URI:
String params = new RequestBuilder().add('order', 'desc').add('sort', 'votes').add('min', min).add('site', site).build(); return 'https://api.stackexchange.com/2.1/questions' + params;3.測試客戶端
客戶端將輸出原始JSON,但是要進行測試,我們需要一個JSON處理庫,特別是Jackson 2 :
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.1.3</version><scope>test</scope> </dependency>我們將看到的測試將與實際的StackExchange API交互:
@Test public void whenRequestIsPerformed_thenSuccess()throws ClientProtocolException, IOException {HttpResponse response = questionsApi.questionsAsResponse(50, Site.serverfault);assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); } @Test public void whenRequestIsPerformed_thenOutputIsJson()throws ClientProtocolException, IOException {HttpResponse response = questionsApi.questionsAsResponse(50, Site.serverfault);String contentType = httpResponse.getHeaders(HttpHeaders.CONTENT_TYPE)[0].getValue();assertThat(contentType, containsString('application/json')); } @Test public void whenParsingOutputFromQuestionsApi_thenOutputContainsSomeQuestions()throws ClientProtocolException, IOException {String questionsAsJson = questionsApi.questions(50, Site.serverfault);JsonNode rootNode = new ObjectMapper().readTree(questionsAsJson);ArrayNode questionsArray = (ArrayNode) rootNode.get('items');assertThat(questionsArray.size(), greaterThan(20)); }第一次測試已驗證API提供的響應確實為200 OK,因此檢索問題的GET請求實際上是成功的。 在確保基本條件之后,我們繼續使用Content-Type HTTP標頭指定的表示形式,該表示形式必須為JSON。 接下來,我們實際解析JSON并驗證輸出中是否確實存在問題–解析邏輯本身是低級且簡單的,足以滿足測試目的。 請注意,這些請求計入API指定的速率限制 -出于這個原因,實時測試不包含在標準Maven版本中:
<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-surefire-plugin</artifactId><version>2.13</version><configuration><excludes><exclude>**/*LiveTest.java</exclude></excludes></configuration> </plugin>4.下一步
當前的Client僅關注StackExchange API發布的許多可用類型中的一種資源。 這是因為它的最初目的是有限的–僅需要使用戶能夠使用StackExchange產品組合中各個站點的問題 。 因此,可以改進客戶端,使其超出此初始用例的范圍,以能夠使用其他類型的API 。 實現也非常原始 -在使用Questions REST Service之后,它只是將JSON輸出作為字符串返回-而不是從該輸出中輸出任何類型的Questions模型。 因此,下一步可能是將JSON解組到適當的域DTO中,然后將其返回而不是原始JSON。
5.結論
本文的目的是演示如何開始與StackExchange API或實際上是基于HTTP的API建立集成。 它涵蓋了如何針對實時API編寫集成測試,以及如何確保端到端交互確實有效。
本文的第二部分將展示如何使用Spring Social庫與Twitter API進行交互,以及如何使用我們在此處構建的StackExchange Client在新的Twitter帳戶上發布問題。
我已經建立了一些Twitter帳戶,現在每天在Twitter上發布各種學科的2個熱門問題:
- SpringAtSO –每天來自StackOverflow的兩個最佳Spring問題
- JavaTopSO –每天來自StackOverflow的兩個最佳Java問題
- AskUbuntuBest –每天來自AskUbuntu的兩個最佳問題
- BestBash –每天來自所有StackExchange網站的兩個最佳Bash問題
- ServerFaultBest –每天來自ServerFault的兩個最佳問題
 該StackExchange Client的完整實現在github上 。 
參考: 使用Spring Social 推銷StackExchange –第一部分,來自JCG合作伙伴 Eugen Paraschiv,來自baeldung博客。
翻譯自: https://www.javacodegeeks.com/2013/02/tweeting-stackexchange-with-spring-social-part-1.html
stackexchange
總結
以上是生活随笔為你收集整理的stackexchange_通过Spring Social推特StackExchange –第1部分的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: GWT HTTP请求替代
- 下一篇: 渴望订阅– RxJava常见问题解答
