LoginSignup
11
13

More than 5 years have passed since last update.

HttpURLConnection とリダイレクトについて

Posted at

初心者向けです

我らが @KeithYokoma が素敵な記事「Java - HttpUrlConnection とエラーハンドリング - Qiita - http://goo.gl/hX9FVV 」を書いていたので、初心者向けにまた書きます。

ないよう

HttpUrlConnection はプロトコルが違うリダイレクトは自動的に処理しないという仕様があります。例えば、 http://hoge.comhttps://gege.com にリダイレクトさせるようなレスポンスを戻してきても、HttpUrlConnection は勝手に https://gege.com につなぐようなことはないということです。

実験

http => https のリダイレクトを実現するために、Google のURL短縮サービス goo.gl を使います。

URL url = new URL("http://goo.gl/fhjaj2");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
Log.d(LOG_TAG, "response code = " + urlConnection.getResponseCode());
// 301 が戻ります
Log.d(LOG_TAG, "Location = " + urlConnection.getHeaderField("Location"));
// https://twitter.com/ です

このとき、レスポンスボディーには以下のHTMLが入っていました

<HTML><HEAD><TITLE>Moved Permanently</TITLE></HEAD><BODY BGCOLOR="#FFFFFF" TEXT="#000000"><H1>Moved Permanently</H1>The document has moved <A HREF="https://twitter.com/">here</A>.</BODY></HTML>

あとがき

  • グロースハッカーはバズワード
11
13
0

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
11
13