2014-06-30 19 views
4

當我試圖讓這樣的噴客戶端 - 處理意想不到的內容類型的應答/ json?

val pipeline: HttpRequest => Future[IdentityData] = sendReceive ~> unmarshal[IdentityData] 
pipeline(Get("http://169.254.169.254/latest/dynamic/instance-identity/document")) 

適當的情況下階層和格式化亞馬遜的身份數據,我收到以下異常

UnsupportedContentType(應爲「應用/ JSON」)

因爲亞馬遜將其回覆標記爲text/plain內容類型。他們也不關心接受標題參數。有沒有一種簡單的方法可以告訴spray-json在解組時忽略這一點?

回答

3

如果你想提取一些IdentityData(這是一個情況下,類定義jsonFormat)從亞馬遜的反應,這是一種有效的JSON,但text/plain上下文類型,你可以簡單地提取文本數據,分析它一個JSON和轉換到你的數據,例如:

entity.asString.parseJson.convertTo(identityDataJsonFormat) 
+0

沒想到這麼簡單。感謝提醒,以檢查簡單的選項:-) –

+0

經過數小時的挫折,這真的幫助。非常感謝! –

5

噴霧郵件列表挖後,我寫的作品

def mapTextPlainToApplicationJson: HttpResponse => HttpResponse = { 
    case [email protected] HttpResponse(_, entity, _, _) => 
    r.withEntity(entity.flatMap(amazonEntity => HttpEntity(ContentType(MediaTypes.`application/json`), amazonEntity.data))) 
    case x => x 
} 

,並在管道

val pipeline: HttpRequest => Future[IdentityData] = sendReceive ~> mapTextPlainToApplicationJson ~> unmarshal[IdentityData] 
pipeline(Get("http://169.254.169.254/latest/dynamic/instance-identity/document")) 

很酷的東西用它的功能在這裏你可以攔截&改變任何的HttpResponse只要你的攔截功能有適當的簽名。

+0

有沒有必要寫你的函數,有'mapHttpResponseEntity'指令 – 4lex1v

+0

而且還存在匹配上的HttpResponse實體和應用'withEntity'沒有必要,因爲它將檢查你的實體參數,並應用它,如果它不同(包括空實體的情況下),所以你可以簡單地做'_.withEntity(..)' – 4lex1v

+0

這個解決方案是好的,但是可以通過確保'HttpCharset '從原始響應的'ContentType'被保留。將新的內容類型值設置爲ContentType(MediaTypes。\ applicaiton/json \',amazonEntity.contentType.charset)' –

1

我想出了@ yevgeniy-mordovkin解決方案的更簡單/更清潔版本。

def setContentType(mediaType: MediaType)(r: HttpResponse): HttpResponse = { 
    r.withEntity(HttpEntity(ContentType(mediaType), r.entity.data)) 
} 

用法:

val pipeline: HttpRequest => Future[IdentityData] = (
     sendReceive 
    ~> setContentType(MediaTypes.`application/json`) 
    ~> unmarshal[IdentityData] 
) 
pipeline(Get("http://169.254.169.254/latest/dynamic/instance-identity/document")) 
+0

只有製作人關心你的要求,這纔會起作用。在我的情況下,它不。 –

+0

我認爲你誤讀我的文章。我做同樣的事情(設置內容類型_after_收到響應),只有代碼更清潔一點。小的改進,沒有激進。 – vadipp

相關問題