为Android连接设置Cookie

时间:2013-05-10 11:06:55

标签: android urlconnection

我需要为URL连接设置Cookie。我是Android新手。在iPhone中,它完成如下:

NSURL *serverURL = [NSURL URLWithString:@"<Server URL>"];

NSHTTPCookie *usernamecookie = [NSHTTPCookie cookieWithProperties:
                                   [NSDictionary dictionaryWithObjectsAndKeys:
                                   [serverURL host], NSHTTPCookieDomain,
                                   [serverURL path], NSHTTPCookiePath,
                                     @"username", NSHTTPCookieName,
                                     @"<username>", NSHTTPCookieValue,
                                     nil]];

NSHTTPCookie *passwordcookie = [NSHTTPCookie cookieWithProperties:
                                   [NSDictionary dictionaryWithObjectsAndKeys:
                                   [serverURL host], NSHTTPCookieDomain,
                                   [serverURL path], NSHTTPCookiePath,
                                     @"password", NSHTTPCookieName,
                                     @"<password>", NSHTTPCookieValue,
                                      nil]];

[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:usernamecookie];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:passwordcookie];

NSData *responseData = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:serverURL] returningResponse:nil error:nil];
NSString *response = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]autorelease];
NSLog(@"response data %@",[response description]);

如果有人对此有所了解,请帮助。

1 个答案:

答案 0 :(得分:3)

Android有一些非常相似的东西。您创建cookie并将其添加到cookie存储中,然后在HTTP连接中的服务器请求时可以使用它们。

要创建和添加cookie,请使用以下代码:

CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
HttpCookie cookie = new HttpCookie("lang", "fr");
cookie.setDomain("twitter.com");
cookie.setPath("/");
cookie.setVersion(0);
cookieManager.getCookieStore().add(new URI("http://twitter.com/"), cookie);

有关详细信息,请参阅HttpUrlConnectionCookieManager