How to download PDF use NSURLSession POST with hea

2019-08-31 12:53发布

问题:

I try this on Postman and it works (got 200), it can download PDF. But when I tried to download it return responseString = {"detail":"JSON parse error - No JSON object could be decoded"} and got 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()
}

How to repair (the correct code) this so when I click button, it automatically download PDF?