swift post 请求没有响应

No response from swift post request

需要执行 post 请求才能完成 oauth2.0 身份验证。

在 curl 中工作正常:

curl -i -X POST -H 'Content-Type: application/x-www-form-urlencoded' -d 'clientId=cgoxyBxM1KVO3pLm5J7VgDVxlP7_33BpPlPXeIaSmoLsTZq8DfyM1svTwi-SU7KJKBRN4V3mIsV7pNNEg610Xw' https://fmsauth.scania.com/auth/S2S4DA/ClientId2Challenge

我得到这样的回应:

{"challenge":"_jEEFcI36cvfMac8BHG8R0iIp4g7I-t0-C9LKAjwl9Y"}

我在 swift 中尝试了同样的操作,但得到的响应为零:

import Foundation

let session = URLSession.shared
let url = URL(string: "https://fmsauth.scania.com/auth/S2S4DA/ClientId2Challenge")!

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let payload = Data("clientId=cgoxyBxM1KVO3pLm5J7VgDVxlP7_33BpPlPXeIaSmoLsTZq8DfyM1svTwi-SU7KJKBRN4V3mIsV7pNNEg610Xw".utf8)

let task = session.uploadTask(with: request, from: payload) { data, response, error in

    if let data = data, let dataString = String(data: data, encoding: .utf8) {
        print(dataString)
    }

    if let httpResponse = response as? HTTPURLResponse {
        print(httpResponse.statusCode)
    }
}

task.resume()

我认为负载数据字符串可能存在问题。我不知道 http post 请求 'data format' 在 curl 和 swift.

中的样子

更新 1

好的,看完你的评论后,这是怎么回事,程序在你的代码执行之前就结束了。一种简单的查看方式是在代码中添加断点。

您可以使用信号量来阻塞当前线程并等待您的 URL 会话完成。

A dispatch semaphore is an efficient implementation of a traditional counting semaphore. Dispatch semaphores call down to the kernel only when the calling thread needs to be blocked. If the calling semaphore does not need to block, no kernel call is made. Apple

此代码将执行您想要的操作。

var sema = DispatchSemaphore( value: 0 )
let session = URLSession.shared
let url = URL(string: "https://fmsauth.scania.com/auth/S2S4DA/ClientId2Challenge")!

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let payload = Data("clientId=cgoxyBxM1KVO3pLm5J7VgDVxlP7_33BpPlPXeIaSmoLsTZq8DfyM1svTwi-SU7KJKBRN4V3mIsV7pNNEg610Xw".utf8)

    let task = session.uploadTask(with: request, from: payload) { data, response, error in

        if let data = data, let dataString = String(data: data, encoding: .utf8) {
            print(dataString)
             sema.signal()
        }

        if let httpResponse = response as? HTTPURLResponse {
            print(httpResponse.statusCode)
        }
    }

    task.resume()
    sema.wait()

第一个post

您的代码有效,我认为您需要启用传输。将此添加到 info.plist

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSExceptionDomains</key>
    <dict>
        <key>somethingthatshouldntworkyourdomain.com</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
            <false/>
        </dict>
    </dict>
</dict>

回应

Code 200

{"challenge":"eeABaKaf2ZdhPEVQ4ru2S58_j37VLetM3pryIP8uiXk"}
<NSHTTPURLResponse: 0x600003be73e0> { URL: https://fmsauth.scania.com/auth/S2S4DA/ClientId2Challenge } { Status Code: 200, Headers {
    "Content-Encoding" =     (
        gzip
    );
    "Content-Length" =     (
        182
    );
    "Content-Type" =     (
        "application/json; charset=utf-8"
    );
    Date =     (
        "Wed, 15 Jan 2020 21:12:31 GMT"
    );
    Server =     (
        "Microsoft-IIS/8.5"
    );
    "Set-Cookie" =     (
        "BIGipServerfmsauth.scania.com_https_pool=!c+BZzlVtgeV0E7NCFLoANbUAp39TaIJT2kJgIPLs8cCAJ4R4UMhNbWVOiSnTd/Cx6OuLMGUfIpke3g==; path=/; Httponly; Secure"
    );
    Vary =     (
        "Accept-Encoding"
    );
    "X-HandlingWebServer" =     (
        sesofms9112
    );
    "X-Powered-By" =     (
        "ASP.NET"
    );
    "owin.RequestId" =     (
        "4dbeb043-0e55-4972-b955-45c28f94aa77"
    );
} }