LoginSignup
2

More than 5 years have passed since last update.

GroovyのURL#getTextや#getBytesでヘッダなどを設定する方法

Posted at

 Groovyでは、URLクラスを使って簡単にファイルをダウンロードできたり、Web APIのレスポンスをテキストファイルとして保存できたりします。

 このようにです。

new File(imageName) << new URL(imageUrl).getBytes()
new File(tempName) << new URL(url).getText()

 さて、これらのメソッドでヘッダなどの設定はできないのでしょうか?

 実はURL#getTextURL#getBytesには次のMapを引数にとるオーバーロードがあります。

 それぞれのドキュメントによると、Mapの要素として次のものが有効なようです。

connectTimeout : the connection timeout
readTimeout : the read timeout
useCaches : set the use cache property for the URL connection
allowUserInteraction : set the user interaction flag for the URL connection
requestProperties : a map of properties to be passed to the URL connection

 この部分のコードを見てみます。

 requestPropertiesで渡したMapは、URL#getBytes(java.util.Map) or URL#getText(java.util.Map)の内部で生成しているURLConnectionsetRequestPropertyの呼び出しに使われます。

 次のコードはUserAgentAccept-Languageを設定して、URL#getText(java.util.Map)を呼び出すコードです。

new File(tempName) << new URL(url).getText(requestProperties: [
    "UserAgent": "YOUR USER AGENT",
    "Accept-Language", "jp"
])

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2