我在向Alamofire发送POST请求时遇到问题。我需要将usser和密码字段作为application / x-www-form-urlencode以及url中的一些查询数据发送。
我正在创建一个URLRequest来处理这个过程,但是我总是得到来自服务器的400响应,所以我猜问题必须是我创建请求的方式。
这是Postman中的示例:我需要在url中发送一个param,另外两个在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)
}
})
谢谢你的帮助。
尝试使用URLComponents从queryParameters创建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
}