HTTPRequest

  1. 4 years ago

    ingurgite

    12 Nov 2019 User since 2018

    Hi,

    I am trying to create an HTTPRequest programmatically (without the IDE's help) that takes a query parameter (page = 0...N) to manage pagination. Unfortunately, I can't figure out how to do it. Below is my code>

    var request = HTTPRequest(url)
    request.method = HTTPMethod.Get
    request.queryParameters = ["page": "0"]
    request.responseSerializerType = HTTPResponseSerializer.JSON
    request.send()

    The request works but no parameter is passed. I tried adding "?page=0" in the URL. It works but then I cannot manipulate the query parameters through a map. Is it a bug or am I doing something wrong?

    Thanks.

  2. andrea

    12 Nov 2019 Administrator User since 2016

    Hi @ingurgite,
    if you programmatically create an HTTPRequest (or if you programmatically set a custom value for the path property) the queryParameters property is ignored. You should instead set the complete path in the initializer method or in the path property, for example:

    var url : String = "https://yourdomain.com/basepath?page=0"
    var request = HTTPRequest(url)
    request.responseSerializerType = HTTPResponseSerializer.JSON
    request.send()
  3. ingurgite

    17 Nov 2019 User since 2018

    Hi @andrea, but that means that I cannot easily change page from 0 to 1 as it was the case with the queryParameters array. I would have (as I am doing right now which is quite annoying) to use a RegEx to detect and replace in the URL. Right?

  4. andrea

    18 Nov 2019 Administrator User since 2016
    Edited 4 years ago by andrea

    Or you can programmatically re-build your path from the queryParameters Map, for example, with the following code:

    request.queryParameters = ["page": 1]
    
    // create the new path string from queryParameters
    var path : String = "?"
    for (var key in request.queryParameters.keys()) {
    	var value = request.queryParameters[key]
    	// add "key=value&" to the path string for each query parameter
    	path += key + "=" + value + "&"
    }
    
    // remove the last "&"
    path = path[0...-2]
    
    // update the request path
    request.path = path

or Sign Up to reply!