如何在swift中使用POST请求附加多个数据。
作为邮递员附加的屏幕截图,选择x - www-form-urlencoded
选项时工作正常
如何在身体上附加5个数据,如'x-www-form-urlencoded'
选项。
这里是代码,
var request = URLRequest(url: urlString)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded;charset=UTF-8", forHTTPHeaderField: "Content-Type")
var urlComponents = URLComponents()
urlComponents.queryItems = [
URLQueryItem(name: “***”, value: “***”),
URLQueryItem(name: "***", value: "***"),
URLQueryItem(name: "***", value: "***"),
URLQueryItem(name: "***", value: "***"),
URLQueryItem(name: "***", value: "***"),
]
request.httpBody = urlComponents.percentEncodedQuery?.data(using: String.Encoding.utf8)
let loadDataTask = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let _ = error{
completion(false,error)
}
else if let response = response as? HTTPURLResponse{
if response.statusCode != 200{
completion(false,error)
}
else{
do{
if let parsedData = try? JSONSerialization.jsonObject(with: data!, options: []){
let ff = parsedData as? Dictionary<String,Any>
print(ff)
}
}
}
}
}//let loadDataTask
loadDataTask.resume()
}
答案 0 :(得分:1)
SWIFT 4:
let url = URL(string: “url”);
var urlRequest = URLRequest(url: url!)
urlRequest.setValue("application/x-www-form-urlencoded",forHTTPHeaderField: "Content-Type")
urlRequest.httpMethod = "POST"
let postString = “paramerter1=value1¶meter2=value2”
urlRequest.httpBody = postString.data(using: .utf8)
答案 1 :(得分:0)
创建http正文的一种简单方法是使用URLComponents
,如下所示:
var request = URLRequest(url: yourUrl)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded;charset=UTF-8", forHTTPHeaderField: "Content-Type")
var urlComponents = URLComponents()
urlComponents.queryItems = [
URLQueryItem(name: "your_first_parameter", value: "someValue"),
URLQueryItem(name: "your_second_parameter", value: "someValue"),
URLQueryItem(name: "your_third_parameter", value: "someValue")
]
request.httpBody = urlComponents.percentEncodedQuery?.data(using: .utf8)