1

I am trying to post a simple string, but I continuously getting the HTTP 415 Unsupported Media Type Error. I tried converting the parameter to JSON still it didn't work.

Method Updated

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()

}

Request

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

ERROR

statusCode should be 200, but is 415 { URL: http://192.168.50.119:8181/rest/items/wemo_lamp_switch } { status code: 415, headers { "Content-Length" = 282; "Content-Type" = "application/json"; Date = "Tue, 12 Sep 2017 08:33:16 GMT"; Server = "Jetty(9.2.19.v20160908)"; } }

I Updated the question with your answers but still getting the same error.

Postman Data

{
    "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"
        }
    ]
}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Sathya Baman
  • 3,424
  • 7
  • 44
  • 77

3 Answers3

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

Also

let theparam = JSONSerialization.data(withJSONObject: parameter)
ovidiur
  • 328
  • 2
  • 9
0

Set your request's Content-Type header to whatever you expect your API to return. If you're sure that it returns a JSON then

request.allHTTPHeaderFields["Content-Type"] = "application/json"
mag_zbc
  • 6,801
  • 14
  • 40
  • 62
0

You are sending a UTF8 encoded String instead of a JSON to the API, hence HTTP error 415. However, a simple String cannot be converted to JSON, it either needs to be part of an array or a dictionary, so you need to figure out the actual format your API is expecting.

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

You might also need to add the Content-Type header to your HTTP headers.

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

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • hy tnx. even after adding that. am getting the same error. – Sathya Baman Sep 12 '17 at 09:26
  • Have you actually managed to get your API to work from any other platforms? You should first make the request work from a testing platform (such as Postman) and include the working request in your question. It really seems like, you don't actually know what format your API is expecting. – Dávid Pásztor Sep 12 '17 at 09:28
  • @David.tnx. I tried with postman as a raw data. it works fine. updated my question with postman data, please check. – Sathya Baman Sep 12 '17 at 09:41
  • @SathyaBaman is that the body of your request or the response headers? You should include any headers you used in Postman, the full URL including any query parameters if used and the request body in your question. – Dávid Pásztor Sep 12 '17 at 09:47
  • @"application/json; charset=UTF-8" try adding the encoding also – ovidiur Sep 12 '17 at 10:34