在Swift中向本地服务器发出发布请求时出现400错误

时间:2020-07-28 19:40:20

标签: swift rest http-parameters

我试图向本地服务器发出http POST请求,但是当我拨打电话时,服务器端出现400错误,因此我认为我在发出请求时会遇到问题Swift代码。我不确定我是否正确设置了JSON正文,但是任何帮助将不胜感激。预先感谢!

交换代码:

    let url = URL(string: "http://127.0.0.1:5000/get-friends")!
    var request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10)
    request.httpMethod = "POST"
    let tempIdDictionary: [String: Int] = ["user_id": 17]
    let jsonBody = try? JSONSerialization.data(withJSONObject: tempIdDictionary, options: .fragmentsAllowed)
    request.httpBody = jsonBody
    
    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        guard let data = data else { return }
        do {
            let friendList = try JSONDecoder().decode(FriendList.self, from: data)
        } catch let jsonErr {
            print(jsonErr)
        }
    }
    task.resume()

用于保存json数据的结构:

struct FriendList: Codable {
    let result: [Int]
}

这是我尝试提出请求时迅速显示的错误:

dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})))

Postman request

1 个答案:

答案 0 :(得分:1)

更新:从您刚刚添加的屏幕快照中可以明显看出,您需要将数据作为form-data而不是json进行传递。添加以下扩展名的方法如下:

extension URLRequest {

    struct MultipartFile {
        var data: Data
        var mimeType, filename: String
    }

    mutating func multipartFormData(
        parameters: [String: String] = [:],
        files: [MultipartFile] = []) {

        var body = Data()
        let boundary = "Boundary-\(UUID().uuidString)"
        let boundaryPrefix = "--\(boundary)\r\n"

        for (key, value) in parameters {
            body + boundaryPrefix
            body + "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n"
            body + "\(value)\r\n"
        }

        for file in files {
            body + boundaryPrefix
            body + "Content-Disposition: form-data; name=\"file\"; filename=\"\(file.filename)\"\r\n"
            body + "Content-Type: \(file.mimeType)\r\n\r\n"
            body.append(file.data)
            body + "\r\n"
        }

        body + "--".appending(boundary.appending("--"))

        httpBody = body
        httpMethod = httpMethod == "GET" ? "POST" : httpMethod
        setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
    }
}

extension Data {

    static func + (data: inout Data, string: String) {
        data.append(Data(string.utf8))
    }
}

然后按如下所示修改请求:

request.httpMethod = "POST"
request.multipartFormData(parameters: ["user_id": 17])
// remove the `JSON` body part
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in