1

我正在尝试发布一个简单的字符串,但我不断收到 HTTP 415 Unsupported Media Type Error。我尝试将参数转换为 JSON 仍然无法正常工作。

方法更新

func requestUsingPostMethod(url: String, parameter: String, completion: @escaping (_ success: [String : AnyObject]) -> Void) {

    //@escaping...If a closure is passed as an argument to a function and it is invoked after the function returns, the closure is @escaping.

    var request = URLRequest(url: URL(string: url)!)
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    request.httpMethod = "POST"
    let postString = parameter


    request.httpBody = try? JSONSerialization.data(withJSONObject: [postString])
      //  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=\(String(describing: 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!)
            return

        }

        let responseString  = try! JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String : AnyObject]
        completion(responseString)


    }

    task.resume()

}

要求

NetworkCall().requestUsingPostMethod(url: "http://192.168.50.119:8181/rest/items/wemo_lamp_switch", parameter: "ON", completion: { response in

            print("--------------------------------------------------------------")
            print(response)
           // let jsonResults = JSON(String: response)
        })

错误

statusCode 应该是 200,但是是 415 { URL: http://192.168.50.119:8181/rest/items/wemo_lamp_switch } { status code: 415, headers { "Content-Length" = 282; “内容类型”=“应用程序/json”;日期 =“2017 年 9 月 12 日星期二 08:33:16 GMT”;服务器=“码头(9.2.19.v20160908)”;} }

我用您的答案更新了问题,但仍然出现相同的错误。

邮递员数据

{
    "id": "6f5d4f8a-612a-10f9-71b5-6dc8ba668885",
    "name": "simpledata",
    "description": "",
    "order": [
        "65df8736-1069-b0f0-3a1d-c318ce1810e0"
    ],
    "folders": [],
    "folders_order": [],
    "timestamp": 1505208950131,
    "owner": 0,
    "public": false,
    "requests": [
        {
            "id": "65df8736-1069-b0f0-3a1d-c318ce1810e0",
            "headers": "",
            "headerData": [],
            "url": "http://192.168.50.119:8181/rest/items/wemo_lamp_switch",
            "queryParams": [],
            "pathVariables": {},
            "pathVariableData": [],
            "preRequestScript": null,
            "method": "POST",
            "collectionId": "6f5d4f8a-612a-10f9-71b5-6dc8ba668885",
            "data": [],
            "dataMode": "raw",
            "name": "http://192.168.50.119:8181/rest/items/wemo_lamp_switch",
            "description": "",
            "descriptionFormat": "html",
            "time": 1505208951279,
            "version": 2,
            "responses": [],
            "tests": null,
            "currentHelper": "normal",
            "helperAttributes": {},
            "rawModeData": "OFF"
        }
    ]
}
4

3 回答 3

3
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

let theparam = JSONSerialization.data(withJSONObject: parameter)
于 2017-09-12T08:49:34.433 回答
0

将您的请求Content-Type标头设置为您希望 API 返回的任何内容。如果你确定它返回一个JSONthen

request.allHTTPHeaderFields["Content-Type"] = "application/json"
于 2017-09-12T08:45:18.087 回答
0

您正在向 API 发送 UTF8 编码的字符串而不是 JSON,因此出现 HTTP 错误 415。但是,简单的字符串无法转换为 JSON,它需要是数组或字典的一部分,因此您需要弄清楚您的 API 所期望的实际格式。

request.httpBody = try? JSONSerialization.data(withJSONObject: [postString])

您可能还需要将Content-Type标头添加到您的 HTTP 标头中。

request.allHTTPHeaderFields["Content-Type"] = "application/json"

于 2017-09-12T09:21:58.133 回答