我目前正在使用异步 NSURLConnection 将 json 数据发布到 ASP.Net WebAPI 资源。正在调用 connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:,并且正在写入正确数量的数据。但是 connection:didReceiveResponse:, connection:didReceiveData: 或 connectionDidFinishLoading: 没有被调用,但最终它放弃了,连接丢失了。
我正在按如下方式设置连接:
NSURL *url = [[NSURL URLWithString:[Common baseUrl]] URLByAppendingPathComponent:@"api/iCat/wishlists/upload"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.f];
NSString *jsonString = [self generateStrippedJsonForWishlist:wishlist];
NSData *requestData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [jsonString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:requestData];
并启动连接:
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
最终,请求将超时并显示“网络连接丢失”错误消息。在我看来,该应用程序似乎从未完全完成编写消息正文。
从 api 方面来看,该方法实际上从未被调用(没有命中断点)。但是,如果我发送没有正文的请求,那么它会发送。
我已经使用 curl 测试了相同的调用,它按预期工作:
curl -v -i -X POST -H "Content-Type: application/json" -d '{"CreatedBy":"iPad Simulator","ContactName":"Ddd","ContactEmail":"ddd","Products":[{"ProductId":117,"ProductName":"Internal doors - deco","Specification":""}]}' http://SCMOBILE02:1861/api/iCat/wishlists/upload