我在使用Alamofire发送POST请求时遇到问题。 我需要将usser和密码字段作为application / x-www-form-urlencode发送,并在URL中发送一些查询数据。
我正在创建一个URLRequest来处理该过程,但是我总是从服务器收到400响应,所以我想问题一定出在我创建请求的方式上。
这是邮递员中的示例: 我需要在url中发送一个参数,并在application / x-www-form-urlencode中发送另外两个参数
Postman 1 - Parameters Postman 2 - ContentType
我需要执行此操作(在Android中是这样)
@FormUrlEncoded
@POST(Constants.AUTH_LDAP)
Call<ResponseBody> authLdap(
@Query(value = Constants.PARAM_REQ, encoded = true) String req,
@Field(Constants.PARAM_LOGIN) String login,
@Field(Constants.PARAM_PASSWORD) String password
);
这就是我很快拥有的
let queryParamters = [Constants.Params.PARAM_REQ:req]
let headers = ["Content-Type": "application/x-www-form-urlencoded"]
let fieldParameters = [
Constants.Params.PARAM_LOGIN : user,
Constants.Params.PARAM_PASSWORD : pass]
let url = URL(string: Constants.EndPoints.AUTH_LDAP)
let request = URLRequest(url: url!)
let encoding = try URLEncoding.default.encode(request, with: queryParamters as Parameters)
let encodingpa = try URLEncoding.httpBody.encode(request, with: fieldParameters as Parameters)
var urlRequest = encodingpa
urlRequest.url = encoding.url
urlRequest.allHTTPHeaderFields = headers
Alamofire.request(urlRequest).responseData(completionHandler: { response in
switch response.result {
case .success:
print("sucess")
print(response.response)
case .failure(let error):
print(error)
}
})
感谢您的帮助。
答案 0 :(得分:0)
尝试使用类似URLComponents的查询参数创建url
var urlComponents = URLComponents(string: Constants.EndPoints.AUTH_LDAP)!
urlComponents.queryItems = [
URLQueryItem(name: Constants.Params.PARAM_REQ, value: req)
]
let headers = ["Content-Type": "application/x-www-form-urlencoded"]
var request = URLRequest(url: urlComponents.url!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: fieldParameters)
request.allHTTPHeaderFields = headers
Alamofire.request(request).responseJSON { response in
}