0
我正在嘗試在iphone中對webservice進行用戶授權。等效的螞蟻測試Java版本是以下代碼:iphone - Authorization Post請願
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", "[email protected]"));
urlParameters.add(new BasicNameValuePair("password", "pass"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
如何使相同的objective-c? 我solutios是:
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];
「編碼」 和 「base64StringFromData」 是一個的外部類的方法Base64編碼(如這裏link1)
是我的代碼嗎? 如何獲得服務器響應? 而我該如何實現java「FIELD」?
任何建議真的很感激。 Tx提前