如何在iOS中发送Get请求后从Web服务获得答案

时间:2011-09-25 17:58:16

标签: objective-c ios web-services nsurlconnection

我是iOS开发的新手,在理解Web服务组织方面存在一些问题。我想向URL发送一个Get查询。我这样做了:

-(BOOL) sendLoginRequest{
NSString *getAction = [NSString stringWithFormat:@"action=%@&username=%password=%@",@"login",self.log.text, self.pass.text];
NSString *getUserName = [NSString stringWithFormat:@"username=%@",self.log.text];
NSString *getPassword = [NSString stringWithFormat:@"username=%@",self.pass.text];

NSData *getDataAction = [getAction dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *getLengthAction = [NSString stringWithFormat:@"%d", [getDataAction length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];

[request setURL:[NSURL URLWithString:@"http:http://www.site.fi/api/"]];

[request setHTTPMethod:@"GET"];

[request setValue:getLengthAction forHTTPHeaderField:@"Content-Length"];

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

[request setHTTPBody:getLengthAction];

self.urlConnection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];

NSAssert(self.urlConnection != nil, @"Failure to create URL connection.");

// show in the status bar that network activity is starting
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}

答案可能是“真实”或“虚假”

但我怎么能接受这个答案呢?

2 个答案:

答案 0 :(得分:0)

发送[self.urlConnection start];并实施NSURLConnectionDelegate方法以接收响应。或者使用ASIHTTPRequest和块处理程序,这对我的思维方式来说更容易为初学者编写,前提是您不需要在iOS 4.1之前的iOS上运行。

您将收集作为NSData返回的数据;只需将其转换为字符串,并在字符串上调用boolValue(检查文档是否有相当奇怪的测试),或者使用一组特定的测试。

答案 1 :(得分:0)

您应该定义下一个方法来获得答案:

  1. 开始连接:[self.urlConnection start];

  2. 检查服务器响应:

    - (void)connection:(NSURLConnection *)theConnection didReceiveResponse:(NSURLResponse *)response

  3. 收集服务器发送给您的数据:

    - (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)data

  4. 务必管理错误:

    - (void)connection:(NSURLConnection *)theConnection didFailWithError:(NSError *)error

  5. 检查收到的数据:

    - (void)connectionDidFinishLoading:(NSURLConnection *)theConnection

  6. 为了更加确定您正确理解我,请检查NSURLConnection Class Reference