在我的 xcode 控制台应用程序(10.12)中,我使用 http post 请求将数据发送到 wcf Web 服务。如果该 Web 服务与 http 一起使用,则没有任何问题。但是,如果我更改为安全 (https) 连接,那么我将无法与 Web 服务进行通信。我收到 404 错误代码。
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);
我正在调用方法:
var params = Dictionary<String,AnyObject>()
params["name"] = "Hi" as AnyObject?
var r = request() r.makeHTTPPostRequest(路径:" https://192.168.1.104/sample/Service1.svc/Test ",params:params)
这是来自服务器的响应:
{ status code: 404, headers {
"Cache-Control" = private;
"Content-Length" = 0;
Date = "Sat, 25 Mar 2017 14:59:29 GMT";
Server = "Microsoft-IIS/7.5";
"Set-Cookie" = "ASP.NET_SessionId=l2omo5wflafesmcw2j23sw4t; path=/; HttpOnly";
"X-AspNet-Version" = "4.0.30319";
"X-Powered-By" = "ASP.NET";}
那么我做错了什么?你有什么主意吗?
提前致谢 !