当我给出相同的参数时,我会在邮递员中得到这样的响应
代码:为什么我在这个 makeMultipartRequest() 调用中没有得到像邮差那样的响应?我哪里错了?如何在解析时获得响应和错误。
func makeMultipartRequest() {
let url = "https://test.com/SaveUndertakingAckowledgement"
let parameters: [String: Any] = [
"SchCode": "Test",
"key": "ndjsfnjkds==",
"UserID": 11,
"UserType": 3,
"UtID": "kfnksdlnfks"
]
Alamofire.upload(multipartFormData: { multipartFormData in
for (key, value) in parameters {
if let data = "\(value)".data(using: .utf8) {
multipartFormData.append(data, withName: key)
}
}
}, to: url) { result in
switch result {
case .success(let upload, _, _):
upload.responseJSON { response in
switch response.result {
case .success(let value):
print("Response JSON: \(value)")
// Handle success response
case .failure(let error):
print("Error: \(error)")
// Handle error
}
}
case .failure(let error):
print("Error: \(error)")
// Handle error
}
}
}
func makePostRequest() {
let url = "https://test.com/SaveUndertakingAckowledgement"
let parameters: [String: Any] = [
"SchCode": "test",
"key": "nsjdkfn--=",
"UserID": 11,
"UserType": 3,
"UtID": "ewiw/D264"
]
Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: nil)
.responseJSON { response in
switch response.result {
case .success(let value):
print("Response JSON only post...: \(value)")
// Handle success response
case .failure(let error):
print("Error only post...: \(error)")
// Handle error
}
}
}
响应 JSON:
{
Message = "No HTTP resource was found that matches the request URI 'https://gfvhv.test.com/SaveUndertakingAckowledgement'.";
MessageDetail = "No action was found on the controller 'User' that matches the request.";
}
关于您的 Postman 屏幕,您需要执行一个“简单”的 POST(无多种形式的部分)并将参数放入 URL 中(而对于 POST,它通常位于
httpBody
中)。
Alamofire 解决方案将是:
AF.request(url,
method: .post,
parameters: parameters,
encoding: URLEncoding(destination: .queryString),
headers: nil) //Put your headers there
使用
URLEncoding(destination: .queryString)
,您应该能够知道将参数放入 URL 中(即作为查询)。
旁注: 您可以使用 POSTMAN 生成
cURL
,也可以使用 Alamofire 生成 cURL
。拥有共同点进行比较并尝试匹配工作解决方案确实很有帮助。
在 Alamofire,你只需要:
Alamofire.request(...)
.cURLDescription {
print("AF cURL generated:\($0)")
}
.response(...) //or .responseJSON(), but it's deprecated, prefers other ones
就你而言,我得到:
$ curl -v \
-X POST \
-H "Accept-Encoding: br;q=1.0, gzip;q=0.9, deflate;q=0.8" \
-H "User-Agent: ... Alamofire/5.4.0" \
-H "Accept-Language: en-US;q=1.0" \
"https://test.com/SaveUndertakingAckowledgement?SchCode=Test&UserID=11&UserType=3&UtID=kfnksdlnfks&key=ndjsfnjkds%3D%3D"
除了 User-Agents、Accept-Language、Accept-Encoding 这些更特定于应用程序/设备且通常不会出现问题的参数外,我们看到参数已添加到 URL 中。