繁体   English   中英

获取一个Objective-C HTTP请求iOS 5

[英]Getting an Objective-C HTTP request iOS 5

我需要使用iPhone的HTTP请求到正在构建的应用程序的PHP脚本。 PHP脚本返回文本字符串。 我见过很多人在谈论ASIHTTPRequest,但它在iOS5下不起作用。 我一直在查看Apple Developer文档,但我不太了解如何使用NSURLRequest。 这是我目前所拥有的:

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脚本中有:if($ _ 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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM