Obj-C NSURLConnection无效

时间:2013-03-06 16:33:12

标签: objective-c webservice-client

所以我试图通过带参数的url将数据发送到web服务。我的代码如下,但它永远不会到达服务器。请求和响应为空。我做错了什么?

-(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 个答案:

答案 0 :(得分:0)

您想要发布一些二进制数据但是您执行GET请求并尝试将二进制文件放入网址。 (不编码)

样本帖子:

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];

另外,请注意同步get是坏的,因为它阻止:)使用异步网络!