微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swift 3 发送 HTTP 请求函数

private func HttpPost(requestURL:String,postString:String) -> [String : AnyObject]
    {
        return HttpSync(requestURL: requestURL,postString: postString,method: "POST");
    }
    private func HttpGet(requestURL:String)->[String : AnyObject]{
        return HttpSync(requestURL: requestURL,postString: "",method: "GET");
    }
    private func HttpSync(requestURL:String,postString:String,method:String)->[String : AnyObject]{
        var request = URLRequest(url: URL(string:requestURL)!)
        request.setValue("application/x-www-form-urlencoded; charset=utf-8",forHTTPHeaderField: "Content-Type")
        request.setValue("application/json; charset=utf-8",forHTTPHeaderField: "Accept")
        if(HttpMeta.Token != ""){
            request.setValue("BEARER " + HttpMeta.Token,forHTTPHeaderField: "Authorization");
        }
        
        request.httpMethod = method
        request.httpBody =  postString.data(using: String.Encoding.utf8);
        
        // print(request.debugDescription)
        
        var result:[String:AnyObject] = [:];
        
        let semaphore = dispatchSemaphore(value:0)
        
        let task = URLSession.shared.dataTask(with: request) { data,response,error in
            guard let data = data,error == nil else {
                //print(error ?? <#default value#>)
                return
            }
            
            do {
                print(data.debugDescription)
                print(response.debugDescription)
                let responSEObject = try JSONSerialization.jsonObject(with: data,options: JSONSerialization.ReadingOptions.allowFragments)
                result = (responSEObject as? [String : AnyObject])!;
                print(result)
                //  print(responSEObject)
                
            } catch let jsonError {
                print(jsonError.localizedDescription)
                //  print("json error: \(jsonError.localizedDescription)")
            }
            
            semaphore.signal()
        }
        task.resume()
        
        _ = semaphore.wait(timeout: .distantFuture)
        
        return result
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐