0

所以我试图通过带有参数的 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);}
4

1 回答 1

0

您想发布一些二进制数据,但您执行 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];

另外,请注意同步获取很糟糕,因为它会阻塞:) 使用异步网络!

于 2013-03-06T16:38:02.153 回答