Search code examples
jsonswiftalamofire

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.

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. but the actual output is time out error


Solution

  • Actually you should change encoding method for get request. You have set encoding: JSONEncoding.default. Instead of that, use 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. So, your api_key=\(api_key) should be in json body.

    I hope this will fix your issue.