简体   繁体   中英

Sending a HTTP request in Scala

How can to send a HTTP request

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

in scala and parse this JSON formatted response.

Thanks in Advance.,

Here is an example based on Dispatch and 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)

To get the libraries you need to add the following to your buildfile. : Example for sbt

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

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

The URL you have given in the example lacks parameters and credentials without those you will get an 400- Error. But it should work if you can fix that issue.

Here is an alternative example based on Scruffy Client

val client = ScruffyClient()

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

val entityAsString = resp.bodyAsString

val marshalledJson = resp.bodyAs[MyCaseClass]

And you need to import:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM