一部の Web サイトのコンテンツの取得に問題があります。国際文字を含む別の URL にリダイレクトする URL に移動しようとすると、Java は通常エラー 404 を取得します。ブラウザでこの URL をたどると、有効なデータが得られます。
たとえば、hXXp://shar.es/cISmv に移動したい (2 つ以上の有効なリンクを投稿することはできません)
ブラウザは hXXp://www.dandy-magazine.com/la-griffe-de-la-tour-d%E2%80%99argent に正しくリダイレクトします。wget から、最初にサイトが既存の「場所: http://www.dandy-magazine.com/la-griffe-de-la-tour-d%E2%80%99argent」でリダイレクト 301 を返すことがわかります。
Java (リダイレクトがオフになっている場合) では、リダイレクト 301 に " Location: http://www.dandy-magazine.com/la-griffe-de-la-tour-dâargent
" が返されます。URL エンコーディングを使用すると、次のようになります: " http://www.dandy-magazine.com/la-griffe-de-la-tour-d%C3%A2%C2%80%C2%99argent
". ご覧のとおり、まったく別のサイトです。
サンプルコード (基本的にバージョン 1 とバージョン 2 は同じことを行います):
// version 1 - let java handle redirects
URL url = new URL("http://shar.es/cISmv");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setInstanceFollowRedirects(true);
con.getResponseCode();
return con.getURL(); // returned url is not what it should be
// version 2 - I want to handle redirects
URL url = new URL("http://shar.es/cISmv");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setInstanceFollowRedirects(false);
con.getResponseCode();
String loc = con.getHeaderField("Location");
// here is the problem, loc is not initialized with a correct url
// returned String corresponds to url returned in version 1
助けてくれてありがとう