2016-05-30 113 views
1

我用阿卡HTTP客戶端2.4.6爲JSON發佈到服務器(服務器需要消息的內容類型是一個應用/ JSON處理):如何設置內容類型?

val request = HttpRequest(uri = "http://localhost:9000/auth/add-user", 
     method = HttpMethods.POST, 
     entity = ByteString(write(createUser))) 
     .withHeaders(headers.`Content-Type`(ContentTypes.`application/json`)) 
     Http().singleRequest(request) 

我收到這樣的警告:

顯式設置HTTP頭'Content-Type:application/json'爲 忽略,顯式爲Content-Type頭不允許。改爲設置 HttpRequest.entity.contentType

和服務器端的錯誤是:

415不支持的媒體類型

如何正確設置的內容類型呢?

回答

3

您需要使用預定義的一組可用的ContentType定義或創建自己的,然後在設置數據時將其傳遞,但​​必須通過withEntity方法完成。

// Making your own, from a string 
    val c1 = ContentType(
    MediaType.custom(
     "my_custom_type", 
     new MediaType.Encoding.Fixed(HttpCharsets.`UTF-8`)) 
    ) 

然後你在請求建設者通過這樣的:

val req = HttpRequest(method = HttpMethods.POST, uri = Uri(url) 
     .withQuery(..) 
     .withHeaders(..) 
     // notice how JSON content type is passed in here. 
     .withEntity(ContentTypes.`application/json`, ByteString(write(createUser)))