I am trying to make an user authorization to webservice in iphone. The equivalent ant test java version is the following code:
HttpPost post = new HttpPost("http://webserviceurl/authuser");
// Header Basic base64 user:pass
post.setHeader("Authorization", "Basic " + Base64.encodeBase64String(StringUtils.getBytesUtf8("myuser:mypassword")));
// FIELD
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("usuario", "doxsi@doxsi.com"));
urlParameters.add(new BasicNameValuePair("password", "pass"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
How can make the same by objective-c? My solutios is:
NSString *urlString = @"http://webserviceurl/authuser";
NSURL *url = [NSURL URLWithString:urlString];
NSString *userName = @"myuser";
NSString *password = @"mypass";
NSError *myError = nil;
// create a plaintext string in the format username:password
NSMutableString *loginString = (NSMutableString*)[@"" stringByAppendingFormat:@"%@:%@", userName, password];
// employ the Base64 encoding above to encode the authentication tokens
NSString *encodedLoginData = [Base64 encode:[loginString dataUsingEncoding:NSUTF8StringEncoding]];
// create the contents of the header
NSString *authHeader = [@"Basic " stringByAppendingFormat:@"%@", encodedLoginData];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
cachePolicy: NSURLRequestUseProtocolCachePolicy
timeoutInterval: 5];
// add the header to the request.
[request addValue:authHeader forHTTPHeaderField:@"Authorization"];
// perform the reqeust
NSURLResponse *response;
NSData *data = [NSURLConnection
sendSynchronousRequest: request
returningResponse: &response
error: &myError];
// webserver's response.
NSString *result = [Base64 base64StringFromData:data length:64];
" encode" and " base64StringFromData" are methods of an externals class Base64 (as here link1)
Is my code right? How can I get the server response? And How I can implement the java "FIELD"?
Any suggestions is really appreciated. Tx in advance
I just resolved and I want to post it if someone havethe same needed.
My code is:
-(IBAction)buttonEntra:(id)sender{
NSLog(@"starting autorization");
NSString *urlString = @"http://sytes.net:8080/rest/checkuser";
NSURL *url = [NSURL URLWithString:urlString];
NSString *serverName = @"serverUSER";
NSString *serverPassword = @"serverPASS";
// create a plaintext string in the format username:password
NSString *authStr = [NSString stringWithFormat:@"%@:%@", serverName, serverPassword];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:@"Basic %@", [Base64 encode:authData ]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
cachePolicy: NSURLRequestUseProtocolCachePolicy
timeoutInterval: 10];
[request setHTTPMethod:@"POST"];
[request setValue:authValue forHTTPHeaderField:@"Authorization"];
//parametros en el body
NSString *userName = usuario;
NSString *userPassword = password;
//esempio doxsi9@hotmail.com - sicignano
NSString *post = [NSString stringWithFormat: @"usuario=%@&password=%@",userName,userPassword];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
// perform the reqeust
NSURLResponse *response;
NSError *myError = nil;
NSData *data = [NSURLConnection
sendSynchronousRequest: request
returningResponse: &response
error: &myError];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
//status code 200 OK - status code 405 no method defined
NSLog(@" connection didReceiveResponse: %@", response);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d {
NSString *string = [[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding];
NSLog(@"connection didReceiveData: %@",string);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"didFailWithError: %@ ", [error localizedDescription]);
[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Servicio no disponible", @"")
message:@"El servidor podria encontrarse en mantenimiento"
delegate:nil
cancelButtonTitle:NSLocalizedString(@"OK", @"")
otherButtonTitles:nil] show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// Do anything you want with it
NSLog(@"connectionDidFinishLoading ");
}
I hope it helps.