2010-09-24 88 views
0

我尝试为输入其数据的用户构建应用程序,并将此数据发布到Web服务器以保存在数据库中。这个Web服务器返回一些数据,如Id或其他东西。 如何才能接收网络服务器返回的数据? 传输已经与NSMutableURLRequest一起工作。但是我寻找一种解决方案来从网络服务器读取答案并将其显示在标签上。如何使用NSMutableURLRequest从网络服务器获取数据

回答

0

它可以如何完成的例子。 Original source

NSString *post = @"key1=val1&key2=val2"; 
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; 

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; 
[request setURL:[NSURL URLWithString:@"http://www.someurl.com"]]; 
[request setHTTPMethod:@"POST"]; 
[request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
[request setHTTPBody:postData]; 

NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self]; 
if (conn) 
{ 
    receivedData = [[NSMutableData data] retain]; 
} 
else 
{ 
    // inform the user that the download could not be made 
} 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    [receivedData setLength:0]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    [receivedData appendData:data]; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    // do something with the data 
    // receivedData is declared as a method instance elsewhere 
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]); 
    NSString *aStr = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding]; 
    NSLog(aStr); 

    // release the connection, and the data object 
    [receivedData release]; 
} 
相关问题