How do I use Scala dispatch to get the URL returned in a 301 redirect?

不羁岁月 提交于 2019-12-21 04:20:33

问题


I am using Scala dispatch HTTP library, version 0.10.1. I make a request to a URL that returns an HTTP 301, permanent redirect. For example, http://wikipedia.com returns a 301 that redirects to http://www.wikipedia.org/. How do I do I use dispatch to get the redirected URL?

Following the tutorial, here's what I've done.

import dispatch._, Defaults._
val svc = url("http://wikipedia.com")
val r = Http(svc OK as.String)
r()

This throws a "Unexpected response status: 301" exception. Presumably I need to either query the r value for the redirected URL, or maybe specify some argument other than OK in its definition, but I can't figure out what to do from the documentation.


回答1:


Configure the underlying asyncClient to follow redirects:

val r = Http.configure(_ setFollowRedirects true)(svc OK as.String)

To get the redirected URL:

val svc = url("http://wikipedia.com/")
val r = Http(svc > (x => x))
val res = r()

println(res.getHeader("Location"))


来源:https://stackoverflow.com/questions/17112493/how-do-i-use-scala-dispatch-to-get-the-url-returned-in-a-301-redirect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!