首先,我不会在 url 中传递用户名和密码。您应该使用 post 来执行此操作。
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://URL/service1.asmx?"]];
NSString *userName = [NSString stringWithFormat:@"parameterUser=%@",txtUserName];
NSString *passWord = [NSString stringWithFormat:@"parameterPass=%@",txtPassword];
NSString *postString = [NSString stringWithFormat:@"username=%@&password=%@",userName, passWord];
NSData *postData = [NSData dataWithBytes: [postString UTF8String] length: [postString length]];
//URL Requst Object
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:TIMEOUT];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody: postData];
这比在 url 中传递敏感数据更安全。
编辑
要获得回复,您可以查看此内容。NSURLConnection和AppleDoc NSURLConnection
您可以使用几种不同的方法来处理来自服务器的响应。您可以使用NSURLConnectionDelegate
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[self.connection start];
连同委托回调:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"didReceiveData");
if (!self.receivedData){
self.receivedData = [NSMutableData data];
}
[self.receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"connectionDidFinishLoading");
NSString *receivedString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"receivedString:%@",receivedString);
}
或者你也可以使用NSURLConnection sendAsynchronousRequest
块
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSString *receivedString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"receivedString:%@",receivedString);
}];