3

That's how I'm doing a POST request

var request = URLRequest(url: url)
let methodString = mehtod.rawValue
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData

if let headers = headers {
    request.set(headers: headers)
}

if let parameters = parameters {
    do {
        let postParams =  try JSONEncoder().encode(parameters)
        let postData = postParams
        request.httpBody = postData
    }
    catch {
        print("error")
    }
}

let session = URLSession.shared

print(request)
print(request.allHTTPHeaderFields)
print(String(data: request.httpBody!, encoding: .utf8)!)
print(request.httpMethod)

session.dataTask(with: request) { (data, response, error) in

    let result: Result<Data>

    if let data = data {
        result = .success(data)
    }
    else if let error = error {
        result = .failure(error)
    }
    else {
        result = .failure(RESTError.unknownError)
    }

    completion(result)

    }.resume()

And this is what I see in Charles

enter image description here

I'm trying to send POST but somehow I'm sending GET request. Also I'm getting error from the server:

{"message":"Method \"GET\" not allowed.","code":"method_not_allowed"}

What can be the reason?

Rob
  • 415,655
  • 72
  • 787
  • 1,044
BergP
  • 3,453
  • 4
  • 33
  • 58

3 Answers3

1

I had the same issue. When redirect occurs iOS makes new request and change POST to GET. Also your body became empty. Double check if you're by accident using http instead https.

You can also implement (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)redirectResponse newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler

but for me that wasn't solution.

Here is more details https://developer.apple.com/forums/thread/12749?answerId=34834022#34834022

zvjerka24
  • 1,772
  • 1
  • 21
  • 27
0

I think you can use session.uploadTask(with: request, from: uploadData).

Scott McKenzie
  • 16,052
  • 8
  • 45
  • 70
0

you need to create your post string as dictionary than convert it to jason string. if you have problem converting your data to jason tell me i ill give you a method for it.

 request.httpMethod = "POST"
  request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData

  let paramString = yourPostDataInJASON!
  print(paramString)
  request.httpBody = paramString.data(using: String.Encoding.utf8)
  request.addValue("application/json", forHTTPHeaderField: "Content-Type")
  request.addValue("application/json", forHTTPHeaderField: "Accept")
Abhay Singh
  • 255
  • 1
  • 8