Sample code for 30+ languages & platforms
Swift

REST Follow Redirects

See more REST Examples

Demonstrates how to follow a 302/303 redirect response.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    // This example requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    let rest = CkoRest()!

    var bTls: Bool = true
    var port: Int = 443
    var bAutoReconnect: Bool = true
    success = rest.connect(hostname: "chilkatsoft.com", port: port, tls: bTls, autoReconnect: bAutoReconnect)
    if success == false {
        print("\(rest.lastErrorText!)")
        return
    }

    // Send a POST to a URL that will respond with a 302 redirect..
    rest.addQueryParam(name: "firstName", value: "John")
    rest.addQueryParam(name: "lastName", value: "Doe")
    var responseText: String? = rest.fullRequestFormUrlEncoded(httpVerb: "POST", uriPath: "/echoPost302.asp")
    if rest.lastMethodSuccess == false {
        print("\(rest.lastErrorText!)")
        return
    }

    var statusCode: Int = rest.responseStatusCode.intValue

    // Examine the response status code
    if statusCode < 300 {
        print("Not a redirect.")
        print("\(responseText!)")
        return
    }

    if statusCode > 399 {
        print("Error response: Status code = \(statusCode)")
        print("\(responseText!)")
        return
    }

    print("Redirect status code = \(statusCode)")

    // The response header will contain a Location field with the redirect URL, such as this:
    // Location: http://www.chilkatsoft.com/echoPostFinal.asp

    // The response status code determines how the client should behave.
    // Here are some common possibilities:

    // 301: Moved Permanently
    // This and all future requests should be directed to the given URI.  (Keep the original HTTP method for the redirect.  In this case, the 
    // original request was a POST, so we POST to the redirect URL.)

    // 302: Found (aka Object Moved aka Moved Temporarily)
    // This is the most popular redirect code, but also an example of industrial practice contradicting the standard. HTTP/1.0 specification (RFC 1945 ) required the client
    // to perform a temporary redirect (the original describing phrase was �Moved Temporarily�), but popular browsers implemented it as a 303 See Other. Therefore, HTTP/1.1
    // added status codes 303 and 307 to disambiguate between the two behaviors. However, the majority of Web applications and frameworks still use the 302 status code
    // as if it were the 303.

    // 303: See Other
    // The response to the request can be found under another URI using a GET method. When received in response to a PUT, it should be assumed that the server has
    // received the data and the redirect should be issued with a separate GET message.

    // 307: Temporary Redirect
    // In this occasion, the request should be repeated with another URI, but future requests can still use the original URI. In contrast to 303, the request method
    // should not be changed when reissuing the original request. For instance, a POST request must be repeated using another POST request.

    print("\(rest.responseHeader!)")

    // Get the redirect URL
    var urlStr: String? = rest.lastRedirectUrl
    if rest.lastMethodSuccess == false {
        print("No Location header found for redirect.")
        return
    }

    let redirectUrl = CkoUrl()!
    redirectUrl.parse(url: urlStr)

    // Prep for the redirect..
    rest.clearAllParts()

    // Disconnect and re-connect.  
    // (This can be skipped if both the host and SSL/TLS conditions are the same.)
    rest.disconnect(maxWaitMs: 100)
    success = rest.connect(hostname: redirectUrl.host, port: redirectUrl.port.intValue, tls: redirectUrl.ssl, autoReconnect: bAutoReconnect)
    if success == false {
        print("\(rest.lastErrorText!)")
        return
    }

    if (statusCode == 301) || (statusCode == 307) {
        // Redirect using a POST, sending the same params to the new destination
        rest.addQueryParam(name: "firstName", value: "John")
        rest.addQueryParam(name: "lastName", value: "Doe")
        responseText = rest.fullRequestFormUrlEncoded(httpVerb: "POST", uriPath: redirectUrl.path)
        if rest.lastMethodSuccess == false {
            print("\(rest.lastErrorText!)")
            return
        }

    }

    if (statusCode == 302) || (statusCode == 303) {
        // Redirect using a GET, sending the query params found in the redirect URL.
        responseText = rest.fullRequestFormUrlEncoded(httpVerb: "GET", uriPath: redirectUrl.pathWithQueryParams)
        if rest.lastMethodSuccess == false {
            print("\(rest.lastErrorText!)")
            return
        }

    }

    // Show the final status code and the response text.
    print("Final status code = \(rest.responseStatusCode.intValue)")

    print("Final response text (HTML, XML, JSON, or whatever..)")
    print("\(responseText!)")

}