Swift 3 - Http发布到Https wcf web服务

时间:2017-03-25 15:06:17

标签: xcode wcf https swift3 urlsession

在我的xcode控制台应用程序(10.12)中,我使用http post请求将数据发送到wcf web服务。如果该Web服务使用http,则没有任何问题。但如果我改为安全(https)连接,那么我无法与Web服务通信。我收到404错误代码。

Notebook python3

和那样的网络服务代码:

class request :NSObject,URLSessionDelegate{


func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
}

func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
    if let err = error {
        print("Error: \(err.localizedDescription)")
    } else {
        print("Error. Giving up")
    }
}


func makeHTTPPostRequest(path: String, params: Dictionary<String,AnyObject>) {
    let request = NSMutableURLRequest(url: NSURL(string: path)! as URL)
    request.httpMethod = "POST"


    do  {
        request.httpBody = try JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions.prettyPrinted)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 10
        configuration.timeoutIntervalForResource = 10

        let session = URLSession(configuration: configuration,delegate: self, delegateQueue: nil)


        let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in

            print(response)

        })
        task.resume()

    }
    catch{

    }

}

我叫方法:

     [WebInvoke(UriTemplate = "/Test", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
    [OperationContract]
    string Test(string name);
#p> params [&#34; name&#34;] =&#34;嗨&#34;作为AnyObject?

var r = request() r.makeHTTPPostRequest(路径:&#34; https://192.168.1.104/sample/Service1.svc/Test&#34;,则params:PARAMS)

这是来自服务器的响应:

var params = Dictionary<String,AnyObject>()

那我做错了什么?你有什么想法吗?

提前致谢!

1 个答案:

答案 0 :(得分:0)

我发现了我的错误,错误的web.config配置。 上面的代码工作正常。

最佳