在Java中处理包含equals(“=”)符号的Cookie

时间:2013-07-09 06:26:04

标签: java cookies httpclient

我按以下方式发送请求。

    HttpClient httpClient=new DefaultHttpClient();
    CookieStore cookieStore=new BasicCookieStore();
    HttpContext httpContext=new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    httpClient.execute(httppost,httpContext);

我在java端的auth cookie就是这样的。

XNlciI6WzU2Mjk0OTk1MzQyMTMxMjAsMCwidEFlbVlLYlpuRXYyc29TNjBSOHhueCIsMTM3MzM0NzcyMCwxMzczMzQ3NzIwXX0 \ 075 | 1373347720 | 5c1ad3ac3828516aa7178f00b3bba961fa29ae9b

(注意\ 075)

在服务器端,它就是这样。

XNlciI6WzU2Mjk0OTk1MzQyMTMxMjAsMCwiejJYUXpQQVhBQ0lQVkdCQU5FMkRtdSIsMTM3MzM0OTIyNiwxMzczMzQ5MjI2XX0

当我使用python请求时,显示的cookie如下所示。

XNlciI6WzU2Mjk0OTk1MzQyMTMxMjAsMCwiclYzYW1FakRHc0dhampDcnhoMlBIVyIsMTM3MzM0OTEzNiwxMzczMzQ5MTM2XX0 = | 1373349137 | e8900c8bfd2972ca4115ef1946b4cdf161a4815a

似乎HttpClient忽略了|之后的位(日期代码和东西)。我错过了什么吗? 我也尝试了所有的cookie策略,没有任何效果。

3 个答案:

答案 0 :(得分:2)

我遇到了同样的问题并通过编写自己的Cookie-Parser方法解决了这个问题:

/**
 * Modified method to parse cookies which contain "=" in their value.<br>
 * The default method {@link HttpServletRequest#getCookies()} cuts off cookies values at the first occurrence of "=".
 * 
 * @param httpRequest
 * @return
 */
public static Map<String, Cookie> parseCookies(HttpServletRequest httpRequest)
{
    return parseCookies(httpRequest.getHeader("Cookie"));
}

public static Map<String, Cookie> parseCookies(String cookieHeader)
{
    Map<String, Cookie> result = new LinkedHashMap<String, Cookie>();
    if (cookieHeader != null)
    {
        String[] cookiesRaw = cookieHeader.split("; ");
        for (int i = 0; i < cookiesRaw.length; i++)
        {
            String[] parts = cookiesRaw[i].split("=", 2);
            String value = parts.length > 1 ? parts[1] : "";
            if (value.length() >= 2 && value.startsWith("\"") && value.endsWith("\""))
            {
                value = value.substring(1, value.length() - 1);
            }
            result.put(parts[0], new Cookie(parts[0], value));
        }
    }
    return result;
}

答案 1 :(得分:1)

好的,我按照以下方式解决了这个问题。在我回答一些事实之前。

  1. Cookie键值对由“=”分隔。
  2. 必须对其中包含“=”的Cookie进行转义(“=”部分)。
  3. 包含“=”的Cookie需要指定为Version1 Cookie
  4. 此类Cookie必须用双引号括起来。
  5. 这是我的整个帖子方法。

        public String doUrlPost(final String connurl,final JSONObject obj) throws IOException{
                  CookieManager cookieManager = new CookieManager();
          CookieHandler.setDefault(cookieManager);
    
          URL url=new URL(connurl);
           HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
             urlConnection.setDoOutput(true);
             urlConnection.setRequestMethod("POST");
             urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
                     //sets the cookie to version 1
             urlConnection.setRequestProperty("Cookie2","$Version=1");
    
             List<HttpCookie> lst=((CookieManager)CookieHandler.getDefault()).getCookieStore().getCookies();
             for(HttpCookie cookie:lst){
    
                 if(cookie.getName().equals("auth")){
                 //double quote your cookie
                  urlConnection.setRequestProperty("Cookie","auth=\""+cookie.getValue()+"\"");
                 }
             }
             urlConnection.setUseCaches(false);      
    
             List<NameValuePair> nameValuePairs = getData(obj);
    
             OutputStream out = urlConnection.getOutputStream();
             BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(out, "UTF-8"));           
             writer.write(getQuery(nameValuePairs));
             writer.close();
    
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            BufferedReader rd=new BufferedReader(new InputStreamReader(in));
            String line="";
            String content="";
            while((line=rd.readLine())!=null){
                content+=line;
            }
            rd.close();
            finalcontent=content;
            urlConnection.disconnect(); 
            return finalcontent;
    } 
    

    获取查询方法

        private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
    {
        StringBuilder result = new StringBuilder();
        boolean first = true;
    
        for (NameValuePair pair : params)
        {
            if (first)
                first = false;
            else
                result.append("&");
    
            result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
        }
    
        return result.toString();
    }
    

答案 2 :(得分:0)

我会使用Jetty的CookieCutter而不是编写我自己的解析器。