SWIFT UI - HTTP POST method sending as GET method
Where as curl post works for the same URL
curl --header "Content-Type: application/json"
--request POST
--data '{"username":"xyz","password":"xyz"}'
http://localhost:5555/post_HTTP_test
//
<NSHTTPURLResponse: 0x60000030a100> { URL: http://localhost:5555/post_HTTP_test } { Status Code: 404, Headers {
//
code-block
func HTTP_POST_2_Test() {
let full_path: String = "http://localhost:5555/post_HTTP_test"
var decodedAnswer: String = ""
if let url = URL(string: full_path) {
var request = URLRequest(url: url)
print("HTTP_POST_2_Test:IN")
let jsonString = """
{
"fld_1": "John",
"Fld_2": 30
}
"""
let jsonData = Data(jsonString.utf8) // Convert string to Data
request.httpMethod = "POST"
request.httpBody = jsonData
do {
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, let response = response, error == nil else{
print("Something wrong?: error: \(error?.localizedDescription ?? "unkown error")")
return
}
print(response)
decodedAnswer = String(decoding: data, as: UTF8.self)
print("Response:",decodedAnswer)
}
task.resume()
}
}
}
In your code, you've configured a URLRequest
object but aren't using it anywhere.
Currently, you're fetching data like this:
URLSession.shared.dataTask(with: url)
This performs a GET request to the specified URL.
Instead, you should use the method that accepts a URLRequest
:
URLSession.shared.dataTask(with: request)