2013-03-06 85 views
0

所以我试图通过带有参数的URL将数据发送到web服务。我有的代码是在下面,但它从来没有命中服务器。请求和响应为空。我究竟做错了什么?Obj-C NSURLConnection不起作用

-(void) postData:(NSString *)data{ 

NSURLResponse* response; 
NSError* error = nil; 
NSString *urlString = [NSString stringWithFormat:@"http://someaddress.com/api?data=%@", data]; 

NSURL *lookupURL = [NSURL URLWithString:urlString]; 

//Create the request. 
NSURLRequest *theRequest=[NSURLRequest requestWithURL:lookupURL]; 

NSData *request = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error]; 

NSString *dataString = [[NSString alloc] initWithData:request encoding:NSUTF8StringEncoding]; 
NSLog(@"-----------------------------"); 
NSLog(@"Request: %@", theRequest); 
NSLog(@"req response: %@", request); 
NSLog(@"response: %@", dataString);} 
+1

请更改标题,因为它工作 – 2013-03-06 16:36:13

+0

但是你的代码做了一个GET没有发布+你不要编码数据 – 2013-03-06 16:36:40

回答

0

你想POST一些二进制数据,但你做了一个GET请求,并尝试把二进制文件放到url中。 (无编码它)

样品后:

NSURL *url = [NSURL URLWithString:@"http://server.com"]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
request.HTTPMethod = @"POST"; 
request.HTTPBody = postData; 
NSData *respData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 

还,注意同步得到的是坏的,因为它块:)使用异步联网!