下面列出了怎么用org.apache.http.impl.cookie.DefaultCookieSpec的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Test that " are not discarded.
* Once this test passes, our hack in HttpWebConnection.HtmlUnitBrowserCompatCookieSpec can safely be removed.
* @see <a href="https://issues.apache.org/jira/browse/HTTPCLIENT-1006">HttpClient bug 1006</a>
* @throws Exception if the test fails
*/
@Test
public void httpClientParsesCookiesQuotedValuesCorrectly() throws Exception {
final Header header = new BasicHeader("Set-Cookie", "first=\"hello world\"");
final DefaultCookieSpec spec = new DefaultCookieSpec();
final CookieOrigin origin = new CookieOrigin("localhost", 80, "/", false);
final List<org.apache.http.cookie.Cookie> list = spec.parse(header, origin);
assertEquals(1, list.size());
assertEquals("\"hello world\"", list.get(0).getValue());
}
/**
* Removes ";jsessionid=<id>" from the url, if the session id is also set in "httpResponse".
* <p>
* This methods first looks for the following header :
*
* <pre>
* Set-Cookie: JSESSIONID=
* </pre>
*
* If found and perfectly matches the jsessionid value in url, the complete jsessionid definition is removed from
* the url.
*
* @param uri
* original uri, may contains a jsessionid.
* @param httpResponse
* the response which set the jsessionId
* @return uri, without jsession
*/
public static String removeSessionId(String uri, HttpResponse httpResponse) {
CookieSpec cookieSpec = new DefaultCookieSpec();
// Dummy origin, used only by CookieSpec for setting the domain for the
// cookie but we don't need it
CookieOrigin cookieOrigin = new CookieOrigin("dummy", Http.DEFAULT_HTTP_PORT, "/", false);
Header[] responseHeaders = httpResponse.getHeaders("Set-cookie");
String jsessionid = null;
for (Header header : responseHeaders) {
try {
List<Cookie> cookies = cookieSpec.parse(header, cookieOrigin);
for (Cookie cookie : cookies) {
if ("JSESSIONID".equalsIgnoreCase(cookie.getName())) {
jsessionid = cookie.getValue();
}
break;
}
} catch (MalformedCookieException ex) {
LOG.warn("Malformed header: " + header.getName() + ": " + header.getValue());
}
if (jsessionid != null) {
break;
}
}
if (jsessionid == null) {
return uri;
}
return UriUtils.removeSessionId(jsessionid, uri);
}