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

400 error when making post request to local server in Swift

我正在尝试向本地服务器发出 http POST 请求,但是当我发出调用时,我在服务器端收到 400 错误,所以我认为有问题我正在 Swift 代码中提出请求。我不确定我是否正确设置了 JSON 正文,但我们将不胜感激任何帮助。提前致谢!

swift代码:

    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]
}

这是在我尝试发出请求时出现在 swift 中的错误:

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

更新:从您刚才添加的屏幕截图可以明显看出,您需要将数据作为 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