-1

我需要为 URL 连接设置 Cookie。我是安卓新手。在 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]);

如果有人对此有任何想法,请提供帮助。

4

1 回答 1

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

于 2013-05-10T11:14:28.267 回答