下面列出了怎么用org.apache.commons.httpclient.Cookie的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Look for session cookies.
*
* @return true if session cookies are available
*/
protected boolean isAuthenticated(HttpMethod method) {
boolean authenticated = false;
if (method.getStatusCode() == HttpStatus.SC_OK
&& "/ews/services.wsdl".equalsIgnoreCase(method.getPath())) {
// direct EWS access returned wsdl
authenticated = true;
} else {
// check cookies
for (Cookie cookie : httpClient.getState().getCookies()) {
// Exchange 2003 cookies
if (cookie.getName().startsWith("cadata") || "sessionid".equals(cookie.getName())
// Exchange 2007 cookie
|| "UserContext".equals(cookie.getName())
) {
authenticated = true;
break;
}
}
}
return authenticated;
}
/**
* Create a <tt>"Cookie"</tt> header value containing all {@link Cookie}s in
* <i>cookies</i> suitable for sending in a <tt>"Cookie"</tt> header
* @param cookies an array of {@link Cookie}s to be formatted
* @return a string suitable for sending in a Cookie header.
* @throws IllegalArgumentException if an input parameter is illegal
*/
public String formatCookies(Cookie[] cookies)
throws IllegalArgumentException {
LOG.trace("enter CookieSpecBase.formatCookies(Cookie[])");
if (cookies == null) {
throw new IllegalArgumentException("Cookie array may not be null");
}
if (cookies.length == 0) {
throw new IllegalArgumentException("Cookie array may not be empty");
}
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < cookies.length; i++) {
if (i > 0) {
buffer.append("; ");
}
buffer.append(formatCookie(cookies[i]));
}
return buffer.toString();
}
/**
* Create a RFC 2109 compliant <tt>"Cookie"</tt> header value containing all
* {@link Cookie}s in <i>cookies</i> suitable for sending in a <tt>"Cookie"
* </tt> header
* @param cookies an array of {@link Cookie}s to be formatted
* @return a string suitable for sending in a Cookie header.
*/
public String formatCookies(Cookie[] cookies) {
LOG.trace("enter RFC2109Spec.formatCookieHeader(Cookie[])");
int version = Integer.MAX_VALUE;
// Pick the lowerest common denominator
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookie.getVersion() < version) {
version = cookie.getVersion();
}
}
final StringBuffer buffer = new StringBuffer();
formatParam(buffer,
new NameValuePair("$Version", Integer.toString(version)),
version);
for (int i = 0; i < cookies.length; i++) {
buffer.append("; ");
formatCookieAsVer(buffer, cookies[i], version);
}
return buffer.toString();
}
/**
* Parse RFC 2965 specific cookie attribute and update the corresponsing
* {@link org.apache.commons.httpclient.Cookie} properties.
*
* @param attribute {@link org.apache.commons.httpclient.NameValuePair} cookie attribute from the
* <tt>Set-Cookie2</tt> header.
* @param cookie {@link org.apache.commons.httpclient.Cookie} to be updated
* @throws MalformedCookieException if an exception occurs during parsing
*/
public void parseAttribute(
final NameValuePair attribute, final Cookie cookie)
throws MalformedCookieException {
if (attribute == null) {
throw new IllegalArgumentException("Attribute may not be null.");
}
if (attribute.getName() == null) {
throw new IllegalArgumentException("Attribute Name may not be null.");
}
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null.");
}
final String paramName = attribute.getName().toLowerCase();
final String paramValue = attribute.getValue();
CookieAttributeHandler handler = findAttribHandler(paramName);
if (handler == null) {
// ignore unknown attribute-value pairs
if (LOG.isDebugEnabled())
LOG.debug("Unrecognized cookie attribute: " +
attribute.toString());
} else {
handler.parse(cookie, paramValue);
}
}
/**
* Performs RFC 2965 compliant {@link org.apache.commons.httpclient.Cookie} validation
*
* @param host the host from which the {@link org.apache.commons.httpclient.Cookie} was received
* @param port the port from which the {@link org.apache.commons.httpclient.Cookie} was received
* @param path the path from which the {@link org.apache.commons.httpclient.Cookie} was received
* @param secure <tt>true</tt> when the {@link org.apache.commons.httpclient.Cookie} was received using a
* secure connection
* @param cookie The cookie to validate
* @throws MalformedCookieException if an exception occurs during
* validation
*/
public void validate(final String host, int port, final String path,
boolean secure, final Cookie cookie)
throws MalformedCookieException {
LOG.trace("enter RFC2965Spec.validate(String, int, String, "
+ "boolean, Cookie)");
if (cookie instanceof Cookie2) {
if (cookie.getName().indexOf(' ') != -1) {
throw new MalformedCookieException("Cookie name may not contain blanks");
}
if (cookie.getName().startsWith("$")) {
throw new MalformedCookieException("Cookie name may not start with $");
}
CookieOrigin origin = new CookieOrigin(getEffectiveHost(host), port, path, secure);
for (Iterator i = getAttribHandlerIterator(); i.hasNext(); ) {
CookieAttributeHandler handler = (CookieAttributeHandler) i.next();
handler.validate(cookie, origin);
}
} else {
// old-style cookies are validated according to the old rules
this.rfc2109.validate(host, port, path, secure, cookie);
}
}
/**
* Return a string suitable for sending in a <tt>"Cookie"</tt> header as
* defined in RFC 2965
* @param cookie a {@link org.apache.commons.httpclient.Cookie} to be formatted as string
* @return a string suitable for sending in a <tt>"Cookie"</tt> header.
*/
public String formatCookie(final Cookie cookie) {
LOG.trace("enter RFC2965Spec.formatCookie(Cookie)");
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (cookie instanceof Cookie2) {
Cookie2 cookie2 = (Cookie2) cookie;
int version = cookie2.getVersion();
final StringBuffer buffer = new StringBuffer();
this.formatter.format(buffer, new NameValuePair("$Version", Integer.toString(version)));
buffer.append("; ");
doFormatCookie2(cookie2, buffer);
return buffer.toString();
} else {
// old-style cookies are formatted according to the old rules
return this.rfc2109.formatCookie(cookie);
}
}
/**
* Parse cookie path attribute.
*/
public void parse(final Cookie cookie, final String path)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (path == null) {
throw new MalformedCookieException(
"Missing value for path attribute");
}
if (path.trim().equals("")) {
throw new MalformedCookieException(
"Blank value for path attribute");
}
cookie.setPath(path);
cookie.setPathAttributeSpecified(true);
}
/**
* Parse cookie port attribute.
*/
public void parse(final Cookie cookie, final String portValue)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (cookie instanceof Cookie2) {
Cookie2 cookie2 = (Cookie2) cookie;
if ((portValue == null) || (portValue.trim().equals(""))) {
// If the Port attribute is present but has no value, the
// cookie can only be sent to the request-port.
// Since the default port list contains only request-port, we don't
// need to do anything here.
cookie2.setPortAttributeBlank(true);
} else {
int[] ports = parsePortAttribute(portValue);
cookie2.setPorts(ports);
}
cookie2.setPortAttributeSpecified(true);
}
}
/**
* Validate cookie port attribute. If the Port attribute was specified
* in header, the request port must be in cookie's port list.
*/
public void validate(final Cookie cookie, final CookieOrigin origin)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
if (cookie instanceof Cookie2) {
Cookie2 cookie2 = (Cookie2) cookie;
int port = origin.getPort();
if (cookie2.isPortAttributeSpecified()) {
if (!portMatch(port, cookie2.getPorts())) {
throw new MalformedCookieException(
"Port attribute violates RFC 2965: "
+ "Request port not found in cookie's port list.");
}
}
}
}
/**
* Parse cookie max-age attribute.
*/
public void parse(final Cookie cookie, final String value)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (value == null) {
throw new MalformedCookieException(
"Missing value for max-age attribute");
}
int age = -1;
try {
age = Integer.parseInt(value);
} catch (NumberFormatException e) {
age = -1;
}
if (age < 0) {
throw new MalformedCookieException ("Invalid max-age attribute.");
}
cookie.setExpiryDate(new Date(System.currentTimeMillis() + age * 1000L));
}
/**
* Return a Cookie array
* and auto importing domain and path when domain was empty.
*
* @param uri required Apache Common VFS supported file systems and response JSON format content.
* @return Cookie[]
*/
Cookie[] getCookies(String uri){
if( null == cookies || 0 == cookies.size()) return null;
for(Cookie cookie: cookies){
if("".equals(cookie.getDomain())){
String domain = uri.replaceAll("^.*:\\/\\/([^\\/]+)[\\/]?.*$", "$1");
cookie.setDomain(domain);
cookie.setPath("/");
cookie.setExpiryDate(null);
cookie.setSecure(false);
}
}
return cookies.toArray(new Cookie[cookies.size()]);
}
/**
* Parse cookie version attribute.
*/
public void parse(final Cookie cookie, final String value)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (cookie instanceof Cookie2) {
Cookie2 cookie2 = (Cookie2) cookie;
if (value == null) {
throw new MalformedCookieException(
"Missing value for version attribute");
}
int version = -1;
try {
version = Integer.parseInt(value);
} catch (NumberFormatException e) {
version = -1;
}
if (version < 0) {
throw new MalformedCookieException("Invalid cookie version.");
}
cookie2.setVersion(version);
cookie2.setVersionAttributeSpecified(true);
}
}
/**
* Return an array of {@link Cookie}s that should be submitted with a
* request with given attributes, <tt>false</tt> otherwise.
* @param host the host to which the request is being submitted
* @param port the port to which the request is being submitted (currently
* ignored)
* @param path the path to which the request is being submitted
* @param secure <tt>true</tt> if the request is using a secure protocol
* @param cookies an array of <tt>Cookie</tt>s to be matched
* @return an array of <tt>Cookie</tt>s matching the criterium
*/
public Cookie[] match(String host, int port, String path,
boolean secure, final Cookie cookies[]) {
LOG.trace("enter CookieSpecBase.match("
+ "String, int, String, boolean, Cookie[])");
if (cookies == null) {
return null;
}
List matching = new LinkedList();
for (int i = 0; i < cookies.length; i++) {
if (match(host, port, path, secure, cookies[i])) {
addInPathOrder(matching, cookies[i]);
}
}
return (Cookie[]) matching.toArray(new Cookie[matching.size()]);
}
/**
* Return a string suitable for sending in a <tt>"Cookie"</tt> header
* as defined in RFC 2109 for backward compatibility with cookie version 0
* @param buffer The string buffer to use for output
* @param cookie The {@link Cookie} to be formatted as string
* @param version The version to use.
*/
private void formatCookieAsVer(final StringBuffer buffer, final Cookie cookie, int version) {
String value = cookie.getValue();
if (value == null) {
value = "";
}
formatParam(buffer, new NameValuePair(cookie.getName(), value), version);
if ((cookie.getPath() != null) && cookie.isPathAttributeSpecified()) {
buffer.append("; ");
formatParam(buffer, new NameValuePair("$Path", cookie.getPath()), version);
}
if ((cookie.getDomain() != null)
&& cookie.isDomainAttributeSpecified()) {
buffer.append("; ");
formatParam(buffer, new NameValuePair("$Domain", cookie.getDomain()), version);
}
}
public int compare(final Object o1, final Object o2) {
Cookie c1 = (Cookie) o1;
Cookie c2 = (Cookie) o2;
String path1 = normalizePath(c1);
String path2 = normalizePath(c2);
if (path1.equals(path2)) {
return 0;
} else if (path1.startsWith(path2)) {
return -1;
} else if (path2.startsWith(path1)) {
return 1;
} else {
// Does not really matter
return 0;
}
}
@Override
public void validate(String host, int port, String path,
boolean secure, final Cookie cookie) throws MalformedCookieException {
// workaround for space in cookie name
String cookieName = cookie.getName();
if (cookieName != null && cookieName.indexOf(' ') >= 0) {
cookie.setName(cookieName.replaceAll(" ", ""));
} else {
cookieName = null;
}
// workaround for invalid cookie path
String cookiePath = cookie.getPath();
if (cookiePath != null && !path.startsWith(cookiePath)) {
cookie.setPath(path);
} else {
cookiePath = null;
}
// workaround for invalid cookie domain
int dotIndex = -1;
if (host.endsWith(cookie.getDomain())) {
String hostWithoutDomain = host.substring(0, host.length()
- cookie.getDomain().length());
dotIndex = hostWithoutDomain.indexOf('.');
}
if (".login.microsoftonline.com".equals(cookie.getDomain())) {
cookie.setDomain(host);
}
if (dotIndex != -1) {
// discard additional host name part
super.validate(host.substring(dotIndex + 1), port, path, secure, cookie);
} else {
super.validate(host, port, path, secure, cookie);
}
if (cookieName != null) {
cookie.setName(cookieName);
}
if (cookiePath != null) {
cookie.setPath(cookiePath);
}
}
/**
* <p>
* 初始化HttpClient对象,同时设置转发应用的Cookie信息。
* 将当前请求中的cookie信息(除去sessionId cookie 和 token cookie)设置到新的请求中来
* </p>
* @param targetAS 转发的目标应用
* @return
*/
public static HttpClient getHttpClient(AppServer targetAS) {
HttpState initialState = new HttpState();
HttpServletRequest request = Context.getRequestContext().getRequest();
javax.servlet.http.Cookie[] cookies = request.getCookies();
cookies = (javax.servlet.http.Cookie[]) EasyUtils.checkNull(cookies, new javax.servlet.http.Cookie[] {});
// 设置转发Cookies信息
AppServer currentAS = Context.getApplicationContext().getCurrentAppServer();
for (javax.servlet.http.Cookie cookie : request.getCookies()) {
String cookieName = cookie.getName();
if (cookieName.equals(currentAS.getSessionIdName())
|| cookieName.equals(RequestContext.USER_TOKEN)) {
continue;
}
// 保存当前应用以外的sessionId信息的cookie一般是以其应用Code命名的,当前应用的则以JSESSIONID命名
if (cookieName.equals(targetAS.getCode())) {
cookieName = targetAS.getSessionIdName();
}
String domain = targetAS.getDomain();
String path = targetAS.getPath();
Cookie apacheCookie = new Cookie(domain, cookieName, cookie.getValue(), path, null, request.isSecure());
initialState.addCookie(apacheCookie);
}
HttpClient client = getHttpClient();
client.setState(initialState);
return client;
}
/**
* 处理二次转发请求(request2)转发成功后 返回的Cookie信息,将这些cookie设置到初始的请求和响应里
* @param cookies
* 注:是org.apache.commons.httpclient.Cookie
* @param targetAppServer
*/
public static void transmitReturnCookies(org.apache.commons.httpclient.Cookie[] cookies, AppServer targetAppServer) {
RequestContext requestContext = Context.getRequestContext();
if (requestContext == null) return;
XHttpServletRequest request = requestContext.getRequest();
HttpServletResponse response = Context.getResponse();
if (response == null || request == null) return;
// 转发返回Cookies
for (int i = 0; i < cookies.length; i++) {
String cookieName = cookies[i].getName();
//如果当前应用本身的cookie,则无需转发
if (cookieName.equals(Context.getApplicationContext().getCurrentAppCode())) continue;
if (cookieName.equals(targetAppServer.getSessionIdName())) {
cookieName = targetAppServer.getCode();
}
String cpath = request.getContextPath();
javax.servlet.http.Cookie cookie = createCookie(cookieName, cookies[i].getValue(), cpath);
cookie.setMaxAge(-1);
cookie.setSecure(request.isSecure());
if (response.isCommitted()) {
response.addCookie(cookie);
}
// 同时也添加到request中,以用于二次、三次的远程接口调用
request.addCookie(cookie);
}
}
/**
* Return a string suitable for sending in a <tt>"Cookie"</tt> header
* @param cookie a {@link Cookie} to be formatted as string
* @return a string suitable for sending in a <tt>"Cookie"</tt> header.
*/
public String formatCookie(Cookie cookie) {
LOG.trace("enter CookieSpecBase.formatCookie(Cookie)");
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
StringBuffer buf = new StringBuffer();
buf.append(cookie.getName());
buf.append("=");
String s = cookie.getValue();
if (s != null) {
buf.append(s);
}
return buf.toString();
}
/**
* Test if a session cookie is created
*
* @throws HttpException
* @throws IOException
*/
@Test
public void testCookieAuthentication() throws HttpException, IOException {
final HttpClient c = getAuthenticatedCookieBasedClient("administrator", "olat");
final Cookie[] cookies = c.getState().getCookies();
assertNotNull(cookies);
assertTrue(cookies.length > 0);
}
/**
* <p>
* 请求转向不同同服务器的其他应用
* </p>
* @param appServer
* @param req
* @param response
* @throws IOException
* @throws BusinessServletException
*/
private void proxy4ForeignApplication(AppServer appServer, HttpServletResponse response) throws IOException, BusinessServletException {
HttpClient client = HttpClientUtil.getHttpClient(appServer); // 创建HttpClient对象
HttpState httpState = client.getState();
/* 设置用户令牌相关Cookie,包括一个token Cookie和一个 sessionId Cookie */
boolean isSecure = Context.getRequestContext().isSecure(); //是否https请求
String currentAppCode = Context.getApplicationContext().getCurrentAppCode(); //当前应用code
String domain = appServer.getDomain();
String path = appServer.getPath();
if (Context.isOnline()) {
httpState.addCookie(new Cookie(domain, RequestContext.USER_TOKEN, Context.getToken(), path, null, isSecure)); //token = ****************
}
if (Environment.getSessionId() != null) {
httpState.addCookie(new Cookie(domain, currentAppCode, Environment.getSessionId(), path, null, isSecure)); // TSS = JSessionId
}
HttpMethod httpMethod = HttpClientUtil.getHttpMethod(appServer); // 创建HttpPost对象(等价于一个Post Http Request)
try {
// 请求
int statusCode = client.executeMethod(httpMethod);
if (statusCode == HttpStatus.SC_OK) {
// 转发返回信息
transmitResponse(appServer, response, client, httpMethod);
}
else if ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
|| (statusCode == HttpStatus.SC_MOVED_PERMANENTLY)
|| (statusCode == HttpStatus.SC_SEE_OTHER)
|| (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
dealWithRedirect(appServer, response, client, httpMethod);
}
} finally {
httpMethod.releaseConnection();
}
}
public HttpMessageTransportData(AuthenticatedUrl url, boolean chunkSupported, long proxyId, Cookie[] cookies)
{
this.url = url;
this.chunkSupported = chunkSupported;
this.proxyId = proxyId;
this.cookies = cookies;
}
/**
* Adds the given cookie into the given list in descending path order. That
* is, more specific path to least specific paths. This may not be the
* fastest algorythm, but it'll work OK for the small number of cookies
* we're generally dealing with.
*
* @param list - the list to add the cookie to
* @param addCookie - the Cookie to add to list
*/
private static void addInPathOrder(List list, Cookie addCookie) {
int i = 0;
for (i = 0; i < list.size(); i++) {
Cookie c = (Cookie) list.get(i);
if (addCookie.compare(addCookie, c) > 0) {
break;
}
}
list.add(i, addCookie);
}
private Cookie[] sort(Cookie[] cookies)
{
Cookie[] result = new Cookie[cookies.length];
System.arraycopy(cookies, 0, result, 0, cookies.length);
Arrays.sort(result, COOKIE_NAME_COMPARATOR);
return result;
}
@Override
public int hashCode()
{
int result = this.authenticatedUrl.hashCode();
for(Cookie c: cookies)
{
result = 31 * result + c.hashCode();
}
return result;
}
public void testCreateSession() throws MalformedURLException
{
SessionAwareFastServletProxyFactory factory = new SessionAwareFastServletProxyFactory();
factory.setUseLocalService(false);
Echo echo = factory.create(Echo.class, this.getJrpipUrl());
MtProxyInvocationHandler invocationHandler = (MtProxyInvocationHandler) Proxy.getInvocationHandler(echo);
Cookie[] cookies = ((HttpMessageTransportData)invocationHandler.getMessageTransportData()).getCookies();
Assert.assertEquals(1, cookies.length);
TestCase.assertEquals("JSESSIONID", cookies[0].getName());
}
public String get(String url, Cookie[] cookies) throws
IOException {
// clearCookies();
GetMethod g = new GetMethod(url);
g.setFollowRedirects(false);
hc.getState().addCookies(cookies);
hc.executeMethod(g);
return g.getResponseBodyAsString();
}
public void addCookie(String cookie, String domain) {
String[] data = cookie.split(";");
for (String s : data) {
String[] kvPair = s.split("=");
if (kvPair.length == 2) {
String name = kvPair[0];
String value = kvPair[1];
if (!name.equals("path") && !name.equals("domain")) {
hc.getState().addCookie(new Cookie(domain, name, value));
}
}
}
}
public String get(String url, Cookie[] cookies) throws
IOException {
// clearCookies();
GetMethod g = new GetMethod(url);
g.setFollowRedirects(false);
hc.getState().addCookies(cookies);
hc.executeMethod(g);
return g.getResponseBodyAsString();
}
public String getCookie() {
Cookie[] cookies = hc.getState().getCookies();
String tmpcookies = "";
for (Cookie c : cookies) {
tmpcookies += c.toString() + ";";
}
return tmpcookies;
}