如何下载PDF使用带有标题和正文参数的NSURLSession POST?

时间:2019-01-02 02:48:32

标签: swift pdf post nsurlsession

我在Postman上尝试了此方法,它可以正常工作(200位),它可以下载PDF。但是,当我尝试下载它时,返回responseString = {“ detail”:“ JSON解析错误-无法解码JSON对象”} 拿到了400。

@IBAction func downloadPDF(_ sender: Any) {
    let url = URL(string: "https://api-apuat2.tokiomarine-life.co.id/sam/money_analysis_report/")!
    var request = URLRequest(url: url)
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwidXNlcl9pZCI6OTg1NSwianRpIjoiZGMzY2Q3ZTE3NjNkNDUwNzg1NjA3NGVjODVhYzA1MTgiLCJleHAiOjE1NDcwMDA0MjJ9.6y92gdz36i1L9mJ3BUYAiEf8xVR2YM85xLiubQELoGA", forHTTPHeaderField: "Authorization")
    request.httpMethod = "POST"
    let postString = "contact_id="
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(error!)")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response!)")
        }

        let responseString = String(data: data, encoding: .utf8)
        print("responseString = \(responseString!)")
    }
    task.resume()
}

如何修复(正确的代码),这样当我单击按钮时,它会自动下载PDF?

0 个答案:

没有答案