我需要知道以下两种url连接方法的区别? 这两种方法有什么意义? 在什么情况下首选哪种方法?
方法1: 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);
方法2:
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怎么办?
问题:对于登录和注册,这些方法非常好,但每当我想插入包含特殊字符(如@,/,_等)的任何字符串时,它都无法执行任何操作。
指导我PLZ。
答案 0 :(得分:2)
即使你实现的方法1也是不完整的,因为NSUrlConnection有很多委托应该被实现来获取数据,处理错误,代理,身份验证等。建议使用第一种方法,但不要使用你使用的方式。在异步行为中使用NSUrlConnection,这样你就不必等到网址加载了。
NSUrlConnection Class Reference
第二种方法只是在遇到NSData中的NSUrl参数时将url作为sson命中。此外,您无法控制Web服务交互。
要获得NSUrlConnection的实现,您可以浏览
Url With Special Characters:-
[NSURL URLWithString:[string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];