2012-12-30 37 views
4

得到以下是在瀏覽器(如Firefox)的一個有效的查詢:執行一個簡單的HTTP和訊

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以防萬一。

+0

什麼'q確定as.String'打印? (另外,你知道301是「永久移動」的代碼,對吧?) –

+0

@rex'(http://www.freesound.org/api/sounds/search GET,dispatch.OkFunctionHandler @ 7fc4fe21)'。我對HTTP沒有很好的瞭解,但是如果我把URL放在瀏覽器中,它就可以完美工作。 –

回答

13

您可以啓用重定向與上Http執行人的configure方法如下:

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

你也可以拉出來Location手動301反應,但是這將是少了很多方便。

+0

非常感謝Rex和Travis;我不知道這個重定向如何工作等,但這個解決方案的工作原理! –

+1

服務器X給了我一個重定向(狀態碼302),並且還向我發送了幾個cookie。這行代碼工作得很好:我被重定向,併發送正確的cookie。不過,我失去了重定向發送的cookies的信息:有沒有辦法讓它們(除了手動處理重定向?) – JohnCastle