作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想知道下面两种url连接方式的区别?这两种方法的意义何在?在什么情况下首选哪种方法?
方法一: 文件.h #导入
#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);
如果我只需要使用 header 信息连接到 url 怎么办?
问题:对于登录和注册,这些方法都很好,但是每当我想插入任何包含特殊字符(如@、/、_等)的字符串时,它都无法执行任何操作。
请指导我。
最佳答案
即使您实现的方法 1 也不完整,因为有许多 NSUrlConnection 的委托(delegate),应该实现这些委托(delegate)以获取数据、处理错误、代理、身份验证等。更明智的做法是使用第一种方法,但不要使用您使用的方式。NSUrlConnection 在行为上是异步的,因此您不必等到加载 url。
NSUrlConnection Class Reference
第二种方法只是在遇到 NSData 中的 NSUrl 参数时将 url 作为 sson 命中。此外,您对 Web 服务交互没有太多控制权。
要获得 NSUrlConnection 的实现,你可以通过
Url With Special Characters:-
[NSURL URLWithString:[string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
关于iphone - URL 连接 : What is the difference between the following?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10549881/
我是一名优秀的程序员,十分优秀!