gpt4 book ai didi

iphone - URL 连接 : What is the difference between the following?

转载 作者:行者123 更新时间:2023-11-28 22:57:13 25 4
gpt4 key购买 nike

我想知道下面两种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 服务交互没有太多控制权。

NSUrl Class Reference

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

NSUrlConnection Tutorial

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com