我遇到了一个问题:"在浏览器中可以正常访问URL,但是用Java的http-get方法访问时会出现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=
value = USE_RESPONSIVE_GUI=1
value = ASP.NET_SessionId=bf0bxkfawdwfr10ipmvviq3d
...
因为服务器只收到了所需数据的三分之一,所以它变得混乱了:你已经登录了!不,等等,你需要登录。不,你已经登录了...
为了解决无限重定向循环的问题,我不得不手动查找重定向并手动解析头部中的“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:
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)) {
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;
}
theurl
是什么? - sunil