我需要为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]);
如果有人对此有所了解,请帮助。
答案 0 :(得分:3)
要创建和添加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);
有关详细信息,请参阅HttpUrlConnection和CookieManager