我跑進「網址在瀏覽器的工作原理的問題,但是當我做HTTP-GET在Java中,我得到一個500錯誤」。
在我的情況下,問題是,普通HTTP-GET在/default.aspx之間的無限重定向循環結束了和/login.aspx
URL oUrl = new URL(url);
HttpURLConnection con = (HttpURLConnection) oUrl.openConnection();
con.setRequestMethod("GET");
...
int responseCode = con.getResponseCode();
發生了什麼事是:服務器提供了一個三部分cookie和con.getResponseCode()僅使用其中一個部分。標題中的Cookie數據是這樣的:
header.key = null
value = HTTP/1.1 302 Found
...
header.key = Location
value = /default.aspx
header.key = Set-Cookie
value = WebCom-lbal=qxmgueUmKZvx8zjxPftC/bHT/g/rUrJXyOoX3YKnYJxEHwILnR13ojZmkkocFI7ZzU0aX9pVtJ93yNg=; path=/
value = USE_RESPONSIVE_GUI=1; expires=Wed, 17-Apr-2115 18:22:11 GMT; path=/
value = ASP.NET_SessionId=bf0bxkfawdwfr10ipmvviq3d; path=/; HttpOnly
...
所以僅接收所需的數據糊塗了三分之一當服務器:你登錄!無需等待,您必須登錄。不,您已登錄,...
要解決無限重定向循環,我必須手動查找重定向並手動解析「Set-cookie」條目的標題。
con = (HttpURLConnection) oUrl.openConnection();
con.setRequestMethod("GET");
...
log.debug("Disable auto-redirect. We have to look at each redirect manually");
con.setInstanceFollowRedirects(false);
....
int responseCode = con.getResponseCode();
有了這個代碼中的Cookie的分析,如果我們在responseCode重定向:
private String getNewCookiesIfAny(String origCookies, HttpURLConnection con) {
String result = null;
String key;
Set<Map.Entry<String, List<String>>> allHeaders = con.getHeaderFields().entrySet();
for (Map.Entry<String, List<String>> header : allHeaders) {
key = header.getKey();
if (key != null && key.equalsIgnoreCase(HttpHeaders.SET_COOKIE)) {
// get the cookie if need, for login
List<String> values = header.getValue();
for (String value : values) {
if (result == null || result.isEmpty()) {
result = value;
} else {
result = result + "; " + value;
}
}
}
}
if (result == null) {
log.debug("Reuse the original cookie");
result = origCookies;
}
return result;
}
來修復它是用於內部服務器錯誤 – 2012-07-30 12:50:23
你試過了什麼'theurl'? – sunil 2012-07-30 13:15:11
@sunil我正在嘗試http://www.rassd.com/1-23544.htm – user1069624 2012-07-30 13:31:13