2017-10-13 272 views
1

我試圖用一個HTTP POST請求的Mailjet API V3發送電子郵件,但發送一封電子郵件,我得到一個錯誤400HTTP POST請求通過Mailjet

我用完全一樣的身體與成功的JavaScript,但我猜錯誤400是與它有關...

任何想法?

var recipients = [Any]() 
recipients.append(["Email": "[email protected]"]) 

var body: [String: Any] = [ 
    "FromEmail": "[email protected]", 
    "FromName": "Me", 
    "Subject": "YEEES", 
    "Text-part": "Greetings from IOS ;)", 
    "Recipients": recipients 
] 

var request = URLRequest(url: self.apiURL) 
    request.httpMethod = "POST" 
    request.setValue("application/json", forHTTPHeaderField: "Content-Type") 
    request.setValue("Authorization", forHTTPHeaderField: "Basic <keysInBase64>") 

    do { 
     request.httpBody = try JSONSerialization.data(withJSONObject: body, options: []) 
    } 
    catch { 
     print("error during JSON serialization") 
     dump(error) 
     return 
    } 

let session = URLSession.shared 
    let task = session.dataTask(with: request, completionHandler: { (data, response, error) in 
     print(error) 
     print(response) 
     print(data) 
    }) 
    task.resume() 
+1

請求中可能存在細微的差異。最簡單的調試方法是使用CharlesProxy。準確記錄實際的HTTP請求 - 然後與您在JavaScript中發送的內容(從瀏覽器開發工具或CharlesProxy獲取)進行比較。 –

+0

@LouFranco非常感謝,我能夠找到查爾斯正在發生的事情。 – Thomas

回答

1

頁眉錯了...

我做:

request.setValue("Authorization", forHTTPHeaderField: "Basic <keysInBase64>") 

相反的:

request.setValue("Basic <keysInBase64>", forHTTPHeaderField: "Authorization") 

使用Charles Proxy通過@LouFranco的建議,我能找到錯誤。