0

我需要知道以下两种url连接方式的区别?这两种方法的意义是什么?在什么情况下首选哪种方法?

方法一:file.h #import

#define kPostURL @"http://localhost/php/register.php"
#define kemail @"email"
#define kpassword @"password"


@interface signup : UIViewController 
{
...
...
NSURLConnection *postConnection;
}
@property ...
...
@end


file.m

NSMutableDictionary *input=[[NSMutableDictionary alloc]init];
...
...
...
NSMutableString *postString = [NSMutableString stringWithString:kPostURL];

[postString appendString: [NSString stringWithFormat:@"?%@=%@", kemail, [input objectForKey:@"email"] ]];
[postString appendString: [NSString stringWithFormat:@"&%@=%@", kpassword, [input objectForKey:@"password"] ]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:postString]];

[request setHTTPMethod:@"POST"];

postConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
NSLog(@"postconnection: %@", postConnection);

NSData *dataURL =  [NSData dataWithContentsOfURL: [ NSURL URLWithString: postString ]];    
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];

NSLog(@"serverOutput = %@", serverOutput);

方法二:

NSString *post =[NSString stringWithFormat:@"email=%@&password=%@",[input objectForKey:@"email"], [input objectForKey:@"password"]];

NSString *hostStr = @"http://localhost/frissbee_peeyush/php/login.php?";
hostStr = [hostStr stringByAppendingString:post];
NSLog(@"HostStr %@",hostStr);
NSData *dataURL =  [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];    
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
NSLog(@"serverOutput %@", serverOutput);

如果我只需要使用标头信息连接到 url 怎么办?

问题:对于登录和注册,这些方法非常好,但是每当我想插入任何包含特殊字符(如@、/、_ 等)的字符串时,它都无法执行任何操作。

请指导我。

4

1 回答 1

2

即使您实现的方法 1 也不完整,因为 NSUrlConnection 有许多委托,应该实现这些委托来获取数据、处理错误、代理、身份验证等。最好使用第一种方法,但不要以您使用的方式使用.NSUrlConnection 在异步行为中,因此您不必等到加载 url。

NSUrlConnection 类参考

第二种方法只是在 NSData 中遇到 NSUrl 参数时将 url 作为 sson 命中。此外,您对 Web 服务交互没有太多控制权。

NSUrl 类参考

要获得 NSUrlConnection 的实现,您可以通过

NSUrlConnection 教程

Url With Special Characters:-
[NSURL URLWithString:[string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 
于 2012-05-11T11:20:50.040 回答