0

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.,

BalaB
  • 3,687
  • 9
  • 36
  • 58
  • 2
    What have you tried so far? Try to solve the individual problems step by step. What resources have you looked into regarding the HTTP request and what did/didn't work? – reto Apr 22 '14 at 07:55
  • I tried Dispatch framework, It didn't help even I tried by adding Thread.Sleep. But didn't worked out. :( – BalaB Apr 22 '14 at 08:26
  • I suggest this library for HTTP GET: https://github.com/scalaj/scalaj-http and this: https://github.com/json4s/json4s for JSON operations. – liosedhel Apr 22 '14 at 08:41

2 Answers2

3

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.

Andreas Neumann
  • 10,734
  • 1
  • 32
  • 52
  • Yes., I tried I get timeout exception in both., spray-client and Dispath., I checked by hitting the URI from browsers it works fine. Later I realised that my program is running behind proxy. How can I overcome such a situation. – BalaB Apr 23 '14 at 06:04
  • Have a look at http://stackoverflow.com/questions/14253515/use-dispatch-0-9-5-behind-proxy there the problem is addressed. – Andreas Neumann Apr 23 '14 at 08:07
0

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"
sksamuel
  • 16,154
  • 8
  • 60
  • 108