如何在Swift中使用HTTP CONNECT隧道

时间:2017-09-18 18:50:32

标签: ios swift http http-tunneling

我正在尝试使用HTTP CONNECT到我的服务器的隧道。到目前为止,我有以下代码:

func executeRequest(_ route: String!, httpMethod: HTTPMethodType, payload: String?, completionHandler:@escaping (_ returnObject: Data?, _ response: URLResponse?, _ error: Error?) -> Void)
{
    let connectRequest = getUrlRequest(HTTPMethodType.connect, "https://host.com")
    let session = URLSession(configuration: .default, delegate: nil, delegateQueue: nil)

    let connectTask = session.dataTask(with: connectRequest) {
        (data: Data?, response: URLResponse?, error: Error?) in

        if (error != nil)
        {
            return;
        }

        let httpStatus = response as? HTTPURLResponse
        let httpStatusCode:Int = (httpStatus?.statusCode)!

        if (httpStatusCode == 200)
        {
            var request = self.getUrlRequest(httpMethod, route!)

            if (payload != nil)
            {
                request.httpBody = payload!.data(using: String.Encoding.utf8)

                let contentLength = String(payload!.lengthOfBytes(using: String.Encoding.utf8))
                request.addValue(contentLength, forHTTPHeaderField: HTTPHeaders.ContentLength.rawValue)
            }

            let task = session.dataTask(with: request) {
                (data: Data?, response: URLResponse?, error: Error?) in

                completionHandler(data, response, error)
            }
            task.resume()
        }
    }
    connectTask.resume();
}

func getUrlRequest(_ httpMethodType: HTTPMethodType, _ url: String) -> URLRequest
{
    let requestUrl = URL(string: url)

    var request = URLRequest(url: requestUrl!)
    request.httpMethod = httpMethodType.rawValue

    // Set headers if necessary
    return request
}

然而,内部任务似乎没有使用隧道。我从初始连接任务中得到200 OK,所以我认为那时候事情还可以。

甚至可以使用Swift中的核心框架来实现这一点?或者我应该看看使用套接字?

0 个答案:

没有答案