iOS Swift POST api with x-www-form-urlencoded



我必须进行API调用,标头为"application/x-www-form-urlencoded",正文"data"为key,vakue为JSON字符串。我必须将数据作为应用程序/x-www-form-urlencoded 格式传递。我已经附上了邮递员的屏幕截图,它工作正常。

[标有标题的图像][带有X-www-form-urlencode标记的帖子数据的图像]

我已经尝试了许多链接,例如使用application/x-www-form-urlencoded的POST请求。但是找不到正确的。

我可以使用其他框架(如Alamofire(来解决此问题。

我为此使用以下代码。

let url = URL(string: "http://mylocalhost/get-user-details")!
var request = URLRequest(url: url)
let jsonString = ["email":"example@domain.com"]
let postData = ["data":jsonString]
let jsonData = try! JSONSerialization.data(withJSONObject: postData, options: .prettyPrinted)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {                                                 // check for fundamental networking error
print("error=(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
print("statusCode should be 200, but is (httpStatus.statusCode)")
print("response = (response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = (responseString)")
}
task.resume()

如果你想使用Alamofire,那么使用这种方法。

func request(_ method: HTTPMethod
, _ URLString: String
, parameters: [String : AnyObject]? = [:]
, headers: [String : String]? = [:]
, onView: UIView?, vc: UIViewController, completion:@escaping (Any?) -> Void
, failure: @escaping (Error?) -> Void) {
Alamofire.request(URLString, method: method, parameters: parameters, encoding: URLEncoding.default, headers: headers)
.responseJSON { response in

switch response.result {
case .success:
completion(response.result.value!)
case .failure(let error):
failure(error)
guard error.localizedDescription == JSON_COULDNOT_SERIALISED else {
return
}
}
}
}

在标头参数中传递此内容

["Content-Type": "application/x-www-form-urlencoded"]

这对我有用,将您的第 6 行替换为:

request.setValue("application/json", forHTTPHeaderField: "Content-Type")

最新更新