2014-04-22 61 views
0

如何發送HTTP請求在斯卡拉發送HTTP請求

https://www.googleapis.com/language/translate/v2

in scala and parse this JSON formatted response。

在此先感謝,

+2

你嘗試過這麼遠嗎?嘗試逐步解決個人問題。你有什麼資源關於HTTP請求,什麼做了/沒有工作? – reto

+0

我試過Dispatch框架,它甚至沒有幫我嘗試添加Thread.Sleep。但沒有解決。 :( – BalaB

+0

我建議這個庫的HTTP GET:https://github.com/scalaj/scalaj-http 和這個:https://github.com/json4s/json4s JSON操作。 – liosedhel

回答

3

這是基於調度JSON4s

import dispatch._ 
import Defaults._ 

import org.json4s._ 
import org.json4s.jackson.JsonMethods._ 

val translateAPI = url("https://www.googleapis.com/language/translate/v2/") 

val response = Http(translateAPI OK as.String) 

val json = parse(response()) //() is added by Dispatch and forces to await the result forever ==  Await.result(response , forever) 

要得到你需要將以下添加到您的構建文件庫的例子。 :示例SBT

libraryDependencies += "org.json4s" %% "json4s-jackson" % "3.2.8" 

libraryDependencies += "net.databinder.dispatch" %% "dispatch-core" % "0.11.0" 

你在例子中的URL參數缺乏和憑據沒有這些,你會得到一個錯誤400-。但如果你能解決這個問題,它應該可以工作。

+0

是的,我試過我在。,spray-client和Dispath中都得到了超時異常,我通過瀏覽器的URI檢查它的工作正常,後來我意識到我的程序運行在代理之後,我該如何克服這種情況 – BalaB

+0

看看http://stackoverflow.com/questions/14253515/use-dispatch-0-9-5-behind-proxy那裏解決了這個問題。 –

0

這裏是基於襤褸的客戶

val client = ScruffyClient() 

val resp = client.prepareGet("https://www.googleapis.com/language/translate/v2").execute() 

val entityAsString = resp.bodyAsString 

val marshalledJson = resp.bodyAs[MyCaseClass] 

替代例子,你需要輸入:

libraryDependencies += "com.sksamuel.scruffy" %% "scruffy-client" % "1.2.5"