【问题标题】:URLSession sends GET request instead of POSTURLSession 发送 GET 请求而不是 POST
【发布时间】:2018-10-29 10:02:11
【问题描述】:

这就是我做 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()

这就是我在查尔斯身上看到的

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

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

可能是什么原因?

【问题讨论】:

标签: ios swift http urlrequest urlsession


【解决方案1】:

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

你也可以实现 (void)URLSession:(NSURLSession *)会话任务:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)redirectResponse newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler

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

这里有更多细节 https://developer.apple.com/forums/thread/12749?answerId=34834022#34834022

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      您需要将您的帖子字符串创建为字典,而不是将其转换为 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")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-04
        • 2015-08-06
        • 2021-10-12
        • 2012-05-06
        相关资源
        最近更新 更多