Hi, everyone,
I want to ask an iPhone application, it is about the adding cookies of GET and POST in NSURLRequest and NSURLResponse.
In my program, the user has to enter uesrname and password. After entered the information, the user will press a button. When the user presses the button, the program will call a function 'pressLoginButton' in the program.
In the program, it will call different url by using GET and POST method. Firstly, the program will call a URL(url_A
) by using GET to retrieve the cookies (I have already done this part). Secondly, the program will call another URL(url_B
) by using POST and the retrieved cookies. However, it has some problems when I pass the cookies to the second url.
(Both of the url are the HTTPS, not the HTTP)
The following is the flow of my program.
1) URL: url_A, method: GET, needed information: none, result: cookie
2) URL: url_B, method: POST, needed information: one of the cookies retrieved from the GET & username & password, result: successful login
The following is my code, can any one help, thank you very much.
// Cookie - declare the NSMutableArray (store all the cookies from all the url)
NSMutableArray *cookiesStoreAll = [[NSMutableArray alloc]init];
NSString *tempName, *tempValue, *cookiesString;
NSUInteger totalNumberOfCookies;
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------- GET ----------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
// doGet: retrieve the cookies from the login page
// doGet - request
NSMutableURLRequest *request_get = [[[NSMutableURLRequest alloc] init] autorelease];
[request_get setURL:[NSURL URLWithString:@"https://url_A"]];
[request_get setHTTPMethod:@"GET"];
[request_get setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request_get setHTTPShouldHandleCookies:YES];
// doGet - response
NSHTTPURLResponse *response_get = nil;
NSError *error_get = nil;
NSData *responseData_get = [NSURLConnection sendSynchronousRequest:request_get returningResponse:&response_get error:&error_get];
NSString *data_get=[[NSString alloc]initWithData:responseData_get encoding:NSUTF8StringEncoding];
⁃
// get the cookies by using the header cookies
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
NSDictionary *headerFields_get = [(NSHTTPURLResponse*)response_get allHeaderFields];
NSURL *urlCookies_get = [NSURL URLWithString:@"https://url_A"];
NSArray *cookies_get = [NSHTTPCookie cookiesWithResponseHeaderFields:headerFields_get forURL:urlCookies_get];
// retrieve the cookies from url by sharedHTTPCookieStore
NSArray *cookiesUse_get = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:urlCookies_get];
NSUInteger numberOfCookiesUse_get = [cookiesUse_get count];
// Cookie - add the array to the cookieStoreAll
[cookiesStoreAll addObjectsFromArray: cookiesUse_get];
totalNumberOfCookies = [cookiesStoreAll count];
NSString *realCookieValue;
// get the needed cookie and convent to the NSString
for(int j=0; j<totalNumberOfCookies; j++)
{
NSString *realCookieName = [[cookiesStoreAll objectAtIndex:j] name];
if([realCookieName isEqualToString: @"neededCookieName"])
{
realCookieValue = [[cookiesStoreAll objectAtIndex:j] value];
cookiesString = [NSString stringWithFormat:@"neededCookieName=%@; ", realCookieValue];
}
}
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------- POST ----------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
// doPost: retrieve the cookies from the login page
// doPost - request (username & password)
CFStringRef escapeChars = (CFStringRef) @":/?#[]@!$&’()*+,;=";
NSString *encodedPassword = (NSString *) CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef) textFieldPassword.text, NULL, escapeChars, kCFStringEncodingUTF8);
NSString *encodedUsername = (NSString *) CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef) textFieldUsername.text, NULL, escapeChars, kCFStringEncodingUTF8);
NSString *encodedString = [NSString stringWithFormat:@"user=%@&pw=%@", encodedUsername, encodedPassword];
NSData *postData = [encodedString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
// doPost - request
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"https://url_B"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"https://url_B" forHTTPHeaderField:@"Referer"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
// doPost - request
NSURLConnection *theConnectionPOST = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[request setValue: (NSString *) cookiesString forHTTPHeaderField:@"Cookie"];
[request setHTTPShouldHandleCookies:YES];
[request setHTTPBody:postData];
// doPost - response (call the request and return the html code)
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
if (!error)
{
NSLog(@"POST: No Error\n");
}
else
{
NSLog(@"\nsomething went wrong: %@\n", [error userInfo]);
}
// *** doPost - response (header file of POST + status code of POST) ***
NSString *responseURL = [[response URL] absoluteString];
NSString *responseTextEncodingName = [response textEncodingName];
NSString *responseMIMEType = [response MIMEType];
NSUInteger responseStatusCode = [response statusCode];
// doPost - response (cookies)
NSDictionary *headerFields = [(NSHTTPURLResponse*)response allHeaderFields];
NSURL *urlCookies = [NSURL URLWithString:@"https://url_B"];
NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:headerFields forURL:urlCookies];
// doPost - response (retrieve the cookies)
NSArray *cookiesPass = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:urlCookies];
[cookiesStoreAll addObjectsFromArray: cookiesPass];
totalNumberOfCookies = [cookiesStoreAll count];
// Cookie - declare the cookiesString
if(totalNumberOfCookies>0)
{
// get the first cookies in the array
tempName = [[cookiesStoreAll objectAtIndex:0] name];
tempValue = [[cookiesStoreAll objectAtIndex:0] value];
cookiesString = [NSString stringWithFormat:@"%@=%@; ", tempName, tempValue];
if(totalNumberOfCookies>1)
{
for(int i=1; i<totalNumberOfCookies ; i++)
{
tempName = [[cookiesStoreAll objectAtIndex:i] name];
tempValue = [[cookiesStoreAll objectAtIndex:i] value];
cookiesString = [NSString stringWithFormat:@"%@%@=%@; ", cookiesString, tempName, tempValue];
}
}
}