URLSession发送GET请求而不是POST

时间:2018-05-18 22:52:50

标签: ios swift http urlrequest urlsession

这就是我正在做POST请求的方式

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

这就是我在查尔斯看到的内容

enter image description here

我正在尝试发送POST但不知何故我正在发送GET请求。 我也从服务器收到错误:

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

可能是什么原因?

3 个答案:

答案 0 :(得分:0)

我认为您可以使用session.uploadTask(with: request, from: uploadData)

答案 1 :(得分:0)

你需要将你的帖子字符串创建为字典,而不是将其转换为jason字符串。 如果您在将数据转换为jason时遇到问题,请告诉我,我会给你一个方法。

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

答案 2 :(得分:0)

我有同样的问题。发生重定向时,iOS会发出新请求,并将POST更改为GET。你的身体也变得空虚。 仔细检查您是否偶然使用http而不是https。

您也可以实施 (void)URLSession:(NSURLSession *)会话任务:(NSURLSessionTask *)任务将执行HTTPRedirection:(NSHTTPURLResponse *)redirectResponse newRequest:(NSURLRequest *)请求完成处理程序:(void(^)(NSURLRequest *))completionHandler

但是对我来说这不是解决方案。

更多详情 https://developer.apple.com/forums/thread/12749?answerId=34834022#34834022

相关问题