Php 获取Objective-C HTTP请求iOS 5
我需要为我正在构建的应用程序使用从iPhone到PHP脚本的HTTP请求。PHP脚本返回一个文本字符串。我见过很多人在谈论AsitpRequest,但它在iOS5下不起作用。我一直在看苹果的开发者文档,但我真的不明白如何使用NSURLRequest。这就是我目前的情况:Php 获取Objective-C HTTP请求iOS 5,php,iphone,objective-c,httprequest,nsurlrequest,Php,Iphone,Objective C,Httprequest,Nsurlrequest,我需要为我正在构建的应用程序使用从iPhone到PHP脚本的HTTP请求。PHP脚本返回一个文本字符串。我见过很多人在谈论AsitpRequest,但它在iOS5下不起作用。我一直在看苹果的开发者文档,但我真的不明白如何使用NSURLRequest。这就是我目前的情况: NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *postLength =
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] init];
[req setURL:[NSURL URLWithString:@"http://location.of.my.php.script"]];
[req setHTTPMethod:@"GET"];
[req setValue:postLength forHTTPHeaderField:@"Content-Length"];
[req setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[req setHTTPBody:postData];
基本上,我想做的是执行HTTP请求,发送一个示例URL:“http://hellothere.com/myscript.php?options=Type&type=foo 然后,在我的PHP脚本中:
如果($\u GET['option']=='Type'){
//做一些事情并返回一个字符串
}
有人能告诉我如何使用NSMutableURLRequest或NSURLConnection的正确方向吗?或者有人能告诉我一个非常基本的教程吗
谢谢我在iOS 5上使用的是这样的ASIHTTPRequest: 您需要实现ASIHTTPRequestDelegate方法。按如下方式发出请求:
ASIFormDataRequest *asiRequest = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlString]];
[asiRequest setPostValue:somPostValue];
asiRequest.delegate = self;
[asiRequest startAsynchronous];
然后是解包响应的委托。这假设响应是JSON格式的
- (void)requestFinished:(ASIHTTPRequest *)request {
// Parse Data
NSString *responseString = [request responseString];
NSDictionary *parsedData = [responseString JSONValue];
// Do whatever you want with this data
}
- (void)requestFailed:(ASIHTTPRequest *)request {
NSError *error = [request error];
NSLog(@"requestFailed: %@", error);
}
ASIHTTPRequest确实可以在iOS 5上运行。我正在使用它。我同意,ASIHTTPRequest可以在iOS 5上运行。如果你使用ARC,它将无法运行。谢谢你,我只是在装傻!那么,如果响应只是一个字符串,我该怎么办?我不确定我是否理解NSDictionary类。根据我的经验,响应通常是XML或JSON格式。我不确定“只是一个字符串”是什么意思。但您可以这样做:NSString*responseString=[request responseString];NSLog(@“%@”,responseString);并查看控制台打印的响应字符串。方法-JSONValue:接受responseString并将JSON响应转换为NSDictionary类。