2017-01-06 26 views
0

我使用Network.Wreq,Control.Lens,Data.Aeson例外:JSONError 「響應的內容類型是」 應用/ random.v4 + JSON 「」 #Haskell

getInfo = do 
    let opts = defaults && header "Accept" .~ ["application/random.v4+json"] "Content-Type" .~ ["application/json"] 
    resp <- asJSON =<< getWith opts "url" :: IO (Response (Map String Value)) 
    let respBody = resp ^. responseBody 
    return respBody 

響應具有Content-Type → application/random.v4+json

當我打電話的功能,它拋出一個異常說

Exception: JSONError "content type of response is \"application/random.v4+json\"" 

但是,當我撥打電話到API,其響應具有簡單Content-Type → application/json而不是有一些奇特Content-Type → application/random.v4+json

我的功能工作所有預期。當迴應contenty-type更改爲application/json之外的任何內容時,會引發上述錯誤。

爲什麼拋出異常?如何使它適用於我的API的所有版本?

**注:API返回的兩個版本相同類型的數據。

回答

1

Network.Wreq.asJSONthrow a JSONError如果響應的內容類型不同於"application/json"

我猜去將明確使用埃宋來響應正文JSON解碼最簡單的方法:

getInfo = do 
    let opts = defaults && header "Accept" .~ ["application/random.v4+json"] "Content-Type" .~ ["application/json"] 
    resp <- getWith opts "url" 
    let respBody = decodeResponseBody $ resp ^. responseBody 
    return respBody 
    where 
    decodeResponseBody :: ByteString -> Map String Value 
    decodeResponseBody body = 
     case eitherDecode' body of 
     Left err -> fail err 
     Right val -> return val 
相關問題