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