我正在尝试通过下面的代码将 JSON 数据发送到 Web 服务器。由于某种原因,该请求似乎没有发出。我好像错过了什么?NSURLConnection (retStr) 的结果也总是空的?
NSDictionary *data = [NSDictionary dictionaryWithObject:@"test sending ios" forKey:@"value1"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:kNilOptions error:&error];
NSURL *url = [NSURL URLWithString:@"http://webserveraddress"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url cachePolicy:nil timeoutInterval:60];
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"];
[req setHTTPMethod:@"POST"];
[req setHTTPBody:jsonData];
NSString *retStr = [[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil] encoding:NSUTF8StringEncoding];