//这里首先提示一下,请求头和请求体都要转为json的字符串,是因为后台接收的格式为raw,如果是其他格式,可能不需要转,转换的方法为:
//首先将字典转为data
let jsonData:Data = try! JSONSerialization.data(withJSONObject: dic, options: []) as Data
//再将data转为字符串
let jsonStr = NSString.init(data: jsonData, encoding: String.Encoding.utf8.rawValue)
****************************。post。******************************************
/// 创建url
let url:URL! = URL(string: “http://”)
/// 发起
var request:URLRequest! = URLRequest.init(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 15)
/// 请求方式
request.httpMethod = "POST"
/// 默认的网络请求方式
// request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
//常用的网络请求方式
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
//请求头的配置,一般请求头说是一个字典,这里要把字典转为json字符串,
request.allHTTPHeaderFields = single.headersDic as? [String : String]
/// 创建请求体 请求体一般也为字典,也要转成json字符串
let bodyData = StringPublic().getHttpBodys(parm: ["UserName":nameTextField.text!]).data(using: .utf8)
//这里请求体为data上面已经转过
request.httpBody = bodyData
/// 接收的数据
var response : URLResponse?
/// 发起网络请求
do {
//解析数据
let res = try! NSURLConnection.sendSynchronousRequest(request, returning: &response)
let dic : NSDictionary = try! JSONSerialization.jsonObject(with: res, options: .allowFragments) as! NSDictionary
print(dic)
}
创建请求头
创建请求体
发起post请求