我跑进“网址在浏览器的工作原理的问题,但是当我做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