Ios 状态代码应为200,但为415

Ios 状态代码应为200,但为415,ios,iphone,swift,http,http-status-code-415,Ios,Iphone,Swift,Http,Http Status Code 415,我试图发布一个简单的字符串,但我不断收到HTTP 415不支持的媒体类型错误。我尝试将参数转换为JSON,但仍然没有成功 方法更新 func requestUsingPostMethod(url: String, parameter: String, completion: @escaping (_ success: [String : AnyObject]) -> Void) { //@escaping...If a closure is passed as an argume

我试图发布一个简单的字符串,但我不断收到HTTP 415不支持的媒体类型错误。我尝试将参数转换为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: }{地位 代码:415,页眉{ “内容长度”=282; “内容类型”=“应用程序/json”; 日期=“2017年9月12日星期二08:33:16 GMT”; Server=“Jetty(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"
        }
    ]
}

将请求的
内容类型
标题设置为您希望API返回的任何内容。如果您确定它返回一个
JSON
,那么

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


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

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

您可能还需要将
内容类型
头添加到HTTP头中


请求。allHTTPHeaderFields[“内容类型”]=“应用程序/json”

415表示“不支持的媒体类型”。您可能需要将accept内容类型添加到
request
中的“application/json”?您正在向WS-waiting发送一个字符串,等待JSONhy tnx。即使加上那个。我得到了同样的错误。即使加上那个。我收到了相同的错误。@“application/json;charset=UTF-8”尝试添加编码alsohy tnx。即使加上那个。我也遇到了同样的错误。你真的设法让你的API在其他平台上工作了吗?您应该首先让请求在测试平台(如Postman)上工作,并将工作请求包含在问题中。看起来,您实际上不知道API需要什么格式。@David.tnx。我试着用邮递员作为原始数据。它很好用。用邮递员数据更新了我的问题,请检查。@SathyaBaman这是请求的正文还是响应的标题?您应该在问题中包括您在Postman中使用的任何标题、包含任何查询参数(如果使用)的完整URL以及请求正文。@“application/json;charset=UTF-8”请尝试添加编码
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let theparam = JSONSerialization.data(withJSONObject: parameter)