[英]How to send json body in get request
I know sending json body in get request is violating http rules, however according to client's requirement the server is accepting json body in get request.so i want to send json body in my get request using alamofire. 我知道在get请求中发送json主体违反了http规则,但是根据客户端的要求,服务器在get request中接受json主体。所以我想使用alamofire在我的get请求中发送json主体。
i tried various parameter encoding types.nothing worked. 我尝试了各种参数编码类型。
func listNews( withCompletionHandler:@escaping (_ status:Bool, _ message: String, _ yearLevels: JSON) -> Void){
let parameters = [
"month": "07",
"year": "2019",
"record_start": 0,
"record_offset": 100
] as [String : Any]
let headers = [
"Content-Type": "application/json"
]
let url = STAFF_SERVICE_URL+"staff/2/news?api_key=\(api_key)"
print("URL > \(url)")
Alamofire.request(url, method: .get,parameters:parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
let statusCode = response.response?.statusCode
print(statusCode ?? "Success Error Code")
if(statusCode==200){
let swiftyJsonVar = JSON(response.result.value!)
print(swiftyJsonVar)
withCompletionHandler(true,"Success",swiftyJsonVar)
}else if(statusCode==400){
withCompletionHandler(false,"System Error. Please try again later.",JSON.null)
}else{
withCompletionHandler(false,"System Error",JSON.null)
}
}
}
i expect array of json objects in response. 我希望得到json对象数组作为响应。 but the actual output is time out error
但是实际输出是超时错误
Actually you should change encoding method for get
request. 实际上,您应该更改
get
请求的编码方法。 You have set encoding: JSONEncoding.default
. 您已设置
encoding: JSONEncoding.default
。 Instead of that, use encoding: URLEncoding.default
. 代替使用
encoding: URLEncoding.default
。
Second thing, if you are sending parameters in json body, then send all parameters instead of some sending with body and some in url. 第二件事,如果要在json正文中发送参数,则发送所有参数,而不是使用body发送某些参数,并使用url发送。 So, your
api_key=\\(api_key)
should be in json body. 因此,您的
api_key=\\(api_key)
应该在json主体中。
I hope this will fix your issue. 希望这能解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.