swift3.0 原生GET请求 POST同理
func getrequest(){
let url = URL(string: "http://117.135.196.139:")
var request = URLRequest(url: url!)
let list = NSMutableArray()
var paramDic = [String: String]()
if paramDic.count > 0 {
//设置为POST请求
request.httpMethod = "GET"
//拆分字典,subDic是其中一项,将key与value变成字符串
for subDic in paramDic {
let tmpStr = "\(subDic.0)=\(subDic.1)"
list.add(tmpStr)
}
//用&拼接变成字符串的字典各项
let paramStr = list.componentsJoined(by: "&")
//UTF8转码,防止汉字符号引起的非法网址
let paraData = paramStr.data(using: String.Encoding.utf8)
//设置请求体
request.httpBody = paraData
}
let configuration:URLSessionConfiguration = URLSessionConfiguration.default
let session:URLSession = URLSession(configuration: configuration)
let task:URLSessionDataTask = session.dataTask(with: request) { (data, response, error)->Void in
if error == nil{
do{
let responseData:NSDictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
print("response:\(response)")
print("responseData:\(responseData)")
}catch{
print("catch")
}
}else{
print("error:\(error)")
}
}
// 启动任务
task.resume()
}