【问题标题】:How to enable cookies when opening a URL's connection打开 URL 连接时如何启用 cookie
【发布时间】:2016-04-28 18:18:57
【问题描述】:

我正在尝试使用以下代码来获取重定向的 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().toString();
 System.out.println(redirctedURL);

【问题讨论】:

  • 问题是如何处理cookies。请看这个thread

标签: java url cookies httpurlconnection urlconnection


【解决方案1】:

使用javaUrlConnection的时候,需要自己处理cookies,读取和设置cookies可以使用URLConnectionsetRequestProperty()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");
}

上面的实现是一种非常愚蠢和粗暴的实现cookie的方式,虽然它有效,但它完全忽略了cookie也可以有一个主机参数来防止标识cookie跨多个主机共享的事实。

比自己动手更好的方法是使用专用于该任务的库,例如 Apache HttpClient。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-24
    • 1970-01-01
    相关资源
    最近更新 更多