SWIFT 网络请求,以form表单形式提交
funcPostRequestSession(urlStr:String,paramers:NSDictionary?,Success:@escaping(_response:Any) ->Void,Fail:@escaping(_error:NSError) ->Void) ->Void{
let _URLStr:String=ServerUrl+urlStr // 请求地址
let _url =URL.init(string:_URLStr)
var urlRequest =URLRequest.init(url: _url!)
urlRequest.httpMethod="POST"
let configuration:URLSessionConfiguration = URLSessionConfiguration.default
letmanager =URLSession(configuration: configuration)
// 设置表单分隔符
letboundary ="Boundary-\(UUID().uuidString)"
urlRequest.setValue("multipart/form-data; boundary=\(boundary)",
forHTTPHeaderField:"Content-Type")
varbodyData =Data()
for(key, value)inparamers! {
// 数据之前要用 --分隔线 来隔开 ,否则后台会解析失败
bodyData.append("--\(boundary)\r\n".data(using:String.Encoding.utf8)!)
bodyData.append("--\(boundary)\r\n".data(using:String.Encoding.utf8)!)
bodyData.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".data(using: String.Encoding.utf8)!)
bodyData.append("\(value)\r\n".data(using:String.Encoding.utf8)!)
}
// --分隔线-- 为整个表单的结束符
bodyData.append("--\(boundary)--\r\n".data(using:String.Encoding.utf8)!)
urlRequest.httpBody= bodyData
LRLog(message:"Request URL \(_URLStr) paramers:\(paramers!))")
let task = manager.dataTask(with: urlRequest){(data,response,error)in
if((error) ==nil){
if((data) ==nil){
return;
}
let httpResponse:HTTPURLResponse= response as! HTTPURLResponse
let statusCode = httpResponse.statusCode
if statusCode ==200{
guard let json =try?JSONSerialization.jsonObject(with: data!, options: .mutableContainers)else{
LRLog(message: data!)
return;
}
LRLog(message:json)
Success(json)
}else{
let errorLocal:NSError=NSError.init(domain:"请求失败", code: statusCode, userInfo: ["error":"请求失败"])
LRLog(message: errorLocal)
Fail(errorLocal)
}
}else{
LRLog(message: error?.localizedDescription)
Fail(error!asNSError)
}
}
task.resume()
}