使用Dispatch执行简单的HTTP GET

时间:2012-12-30 14:36:39

标签: scala http scala-dispatch

以下是浏览器中的有效查询(例如Firefox):

http://www.freesound.org/api/sounds/search/?q=barking&api_key=074c0b328aea46adb3ee76f6918f8fae

产生JSON文档:

{
    "num_results": 610, 
    "sounds": [
        {
            "analysis_stats": "http://www.freesound.org/api/sounds/115536/analysis/", 
            "analysis_frames": "http://www.freesound.org/data/analysis/115/115536_1956076_frames.json", 
            "preview-hq-mp3": "http://www.freesound.org/data/previews/115/115536_1956076-hq.mp3", 
            "original_filename": "Two Barks.wav", 
            "tags": [
                "animal", 
                "bark", 
                "barking", 
                "dog", 
                "effects", 
 ...

我正在尝试使用Dispatch 0.9.4执行此查询。这是一个build.sbt

scalaVersion := "2.10.0"

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

sbt console开始,我执行以下操作:

import dispatch._
val q = url("http://www.freesound.org/api/sounds/search")
   .addQueryParameter("q", "barking")
   .addQueryParameter("api_key", "074c0b328aea46adb3ee76f6918f8fae")
val res = Http(q OK as.String)

但承诺总是以下列错误完成:

res0: dispatch.Promise[String] = Promise(!Unexpected response status: 301!)

那么我做错了什么? Here is the API documentation以防万一。

1 个答案:

答案 0 :(得分:13)

您可以使用configure执行程序上的Http方法启用重定向:

Http.configure(_ setFollowRedirects true)(q OK as.String)

你也可以手动从Location响应中取出301,但这样做会不太方便。