我在獲取某些網站的內容時遇到問題。當我嘗試導航到重定向到包含國際字符的另一個url的url時,java通常會收到404錯誤。當我在瀏覽器中關注此URL時,我會得到有效的數據。Java重定向URL中的HttpUrlConnection國際字符
例如,我想轉到hXXp://shar.es/cISmv(不能發佈超過2個的有效鏈接)
瀏覽器重定向正確我hXXp://www.dandy-magazine。 com/la-griffe-de-la-tour-d%E2%80%99%。從wget我可以看到,最初的網站返回重定向301與現有的「位置:http://www.dandy-magazine.com/la-griffe-de-la-tour-d%E2%80%99argent」
在java(whith重定向關閉)它返回重定向301與「Location: http://www.dandy-magazine.com/la-griffe-de-la-tour-dâargent
」。使用url編碼ot看起來像這樣:「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
THX的幫助
請小心使用正確的字符集編碼。您發佈的第一個鏈接可能使用iso 8859-1編碼,而第二個鏈接使用unicode編碼。 – Twilite
嗨,thx評論。我稍微澄清了這個問題。基本上我的問題是,當我想從java和web瀏覽器訪問同一個站點時,我得到了不同的重定向結果。我懷疑問題可能出在字符編碼上,但我怎麼知道使用了什麼編碼?我該如何設置它? – Caldur