Hi, been searching through the API and Github - is...
# http4k
a
Hi, been searching through the API and Github - is there a simple function to construct a 301/2/7/8 redirected URL, regardless if
Location
header is absolute
<https://www.mysite.com/foo/bar/page.htm>
or relative
/foo/bar/page.htm
or just
page.htm
(not sure if the last one is legal, although plenty of servers produce non-compliant responses). I built a pretty simple implementation but I may have missed edge cases. Thanks!
d
I've never seen the last one myself.. There isn't a dedicated function to build the redirect, but I'd write it like:
Copy code
Response(Status.SEE_OTHER).with(Header.LOCATION of Uri.of('<http://this_can_have_a_server/or_be_just_a_path'))>
a
Hi, sorry I was unclear, I'm trying to interpret a Response (not build one). My function is like
Copy code
if (locationHeader.startsWith("http"))   locationHeader else java.net.URI(originalRequest.uri.scheme, originalRequest.uri.host, locationHeader, "").toString()
d
there's no function to do that, but I'd probably use a filter and then you don't have to mess around higher up the stack:
Copy code
val completeHost = Filter { next ->
        { req ->
            next(req).run {
                if (status.redirection) {
                    val redirect = Header.LOCATION(this)
                    when {
                        redirect.host != req.uri.host -> removeHeader("host")
                            .with(Header.LOCATION of redirect.scheme(req.uri.scheme).authority(req.uri.authority))

                        else -> this
                    }
                } else this
            }
        }
    }
a
thank you for that. I dug around on okhttp's codebase to see how it handles redirects, it sends the original url and the location header value to its
commonParse
function which is 150+ lines. that is overkill for my use case, I think some mix of mine and yours will be sufficient 👍
d
btw - there is a follow redirects filter that you can use to automatically make the request to the new location- would that help in this case?
a
Normally yes, of course, however this project is actually a weird use-case where we manually construct each request, including the 30x redirects (because a number of servers produce non-RFC-compliant responses). Thanks for the help!