Java 如何在打开URL时启用Cookie';s连接
我正在尝试使用以下代码获取重定向的URL,然后对其进行一些处理。但是当我打印重定向链接时,它会转到一个页面,通知没有cookie。如何在打开url连接时启用CookieJava 如何在打开URL时启用Cookie';s连接,java,url,cookies,httpurlconnection,urlconnection,Java,Url,Cookies,Httpurlconnection,Urlconnection,我正在尝试使用以下代码获取重定向的URL,然后对其进行一些处理。但是当我打印重定向链接时,它会转到一个页面,通知没有cookie。如何在打开url连接时启用Cookie String url = "http://dx.doi.org/10.1137/0210059"; URLConnection con = new URL( url ).openConnection(); con.getInputStream(); String redirctedURL= con.getURL().to
String url = "http://dx.doi.org/10.1137/0210059";
URLConnection con = new URL( url ).openConnection();
con.getInputStream();
String redirctedURL= con.getURL().toString();
System.out.println(redirctedURL);
使用java
UrlConnection
时,您应该自己处理cookies,要读取和设置cookies,您可以使用UrlConnection
的setRequestProperty()
和getHeaderField()
剩下的部分是自己解析cookies,下面是一个示例:
Map<String, String> cookie = new HashMap<>();
public URLConnection doConnctionWithCookies(URL url) {
StringBuilder builder = new StringBuilder();
builder.append("&");
for(Map.Entry<String,String> entry : cookie.entrySet()) {
builder.append(urlenEncode(entry.getKey()))
.append("=")
.append(urlenEncode(entry.getValue()))
.append("&");
}
builder.setLength(builder.length() - 1);
URLConnection con = url.openConnection();
con.setRequestProperty("Cookie", builder.toString());
con.connect();
// Parse cookie headers
List<String> setCookie = con.getHeaderFields().get("set-cookie");
// HTTP Spec state header fields MUST be case INsentive, I expet the above to work with all servers
if(setCookie == null)
return con;
// Parse all the cookies
for (String str : setCookie) {
String[] cookieKeyValue = str.split(";")[0].split("=",2);
if (cookieKeyValue.length != 2) {
continue;
}
cookie.put(urlenDecode(cookieKeyValue[0]), urlenDecode(cookieKeyValue[1]));
}
return con;
}
public String urlenEncode(String en) {
return URLEncoder.encode(en, "UTF-8");
}
public String urlenDecode(String en) {
return URLDecoder.decode(en, "UTF-8");
}
Map cookie=newhashmap();
公用URL连接doConnctionWithCookies(URL){
StringBuilder=新的StringBuilder();
建筑商。追加(“&”);
对于(Map.Entry:cookie.entrySet()){
append(urlenEncode(entry.getKey()))
.append(“=”)
.append(urlenEncode(entry.getValue()))
.附加(“&”);
}
builder.setLength(builder.length()-1);
URLConnection con=url.openConnection();
con.setRequestProperty(“Cookie”,builder.toString());
con.connect();
//解析cookie头
List setCookie=con.getHeaderFields().get(“设置cookie”);
//HTTP规范状态头字段必须不区分大小写,我希望上面的内容能够与所有服务器一起使用
if(setCookie==null)
返回con;
//解析所有的cookies
for(字符串str:setCookie){
字符串[]cookieKeyValue=str.split(“;”)[0]。split(“=”,2);
如果(cookieKeyValue.length!=2){
继续;
}
put(urlenDecode(cookieKeyValue[0])、urlenDecode(cookieKeyValue[1]);
}
返回con;
}
公共字符串urlenEncode(字符串en){
返回URLEncoder.encode(en,“UTF-8”);
}
公共字符串urlenDecode(字符串en){
返回URLDecover.decode(en,“UTF-8”);
}
上面的实现是实现cookie的一种非常愚蠢和粗糙的方式,虽然它可以工作,但它完全忽略了这样一个事实,即cookie也可以有一个主机参数,以防止标识cookie在多个主机之间共享
比自己动手更好的方法是使用Apache HttpClient之类的任务专用库。问题是如何处理cookie。请看这个