簡體   English   中英

postWith 是否切換了我的請求的內容類型?

[英]Is postWith switching my request's Content-Type?

無論我輸入什么值作為請求的“內容類型”,我發出的傳出請求似乎都將其替換為“application/x-www-form-urlencoded”。 我試圖點擊的應用程序需要“application/json”。 我的代碼基本上如下。

{-# LANGUAGE OverloadedStrings #-}

import Network.Wreq

...

submissionResources = ["https://widgets.example.com/v2/widgets/request"]

sendWidgetToEndpoint submissionResources workingToken key widgetArray = do
    let opts            = defaults & header "Content-Type"  .~ ["application/json"]
                                   & header "apikey"        .~ [key]
                                   & header "Authorization" .~ [workingToken]
        endPointURL     = head submissionResources 
        widgetId        = widgetArray !! 0
        numberOfWidgets = widgetArray !! 1
        widgetText      = widgetArray !! 2
    submissionResult <- postWith opts endPointURL [ "widgetId"     := widgetId
                                                  , "numWidgets"   := numberOfWidgets
                                                  , "widgetText"   := widgetText
                                                  ]
    return submissionResult

我的問題是我不斷從這個端點返回Status {statusCode = 415, statusMessage = "Unsupported Media Type"} ,我相信這是因為我發送的請求似乎覆蓋了“Content-Type”我的頭。 我曾嘗試使用“application/json”和“text/plain”,但我得到的響應總是向我表明我發送的所有標頭都按預期顯示,除了 Content-Type 總是變成“application/x-www” -form-urlencoded”。

如何確保 wreq 在我的請求標頭中保留“Content-Type: application/json”?

編輯:我正在通過 API 服務器在回復我時告訴我的內容來確定原始請求中的標頭。

代碼段中postWith的最后一個參數的類型是[FormParam] ,該類型強制 Content-Type 進行 urlencoded。

要發送 JSON,請發送ValueEncoding類型的內容(來自Data.Aeson )。

import Data.Aeson (pairs, (.=))

  ...
  -- also remove the "Content-Type" field from opts
  submissionResult <- postWith opts endpointURL $ pairs
    ( "widgetId" .= widgetId <>
      "numWidgets" .= numberOfWidgets <>
      "widgetText" .= widgetText )
  ...

Content-Type 由您通過Postable實例傳遞給postWith的有效負載設置。 如果您想使用另一個 Content-Type 標頭,請使用Postable實例定義您自己的類型,您可以在其中設置適當的 Content-Type。 您也可以選擇不在Postable實例中設置任何 Content-Type,因此您可以通過選項進行設置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM