我正在使用包含数百个位置点的文档设置异步发布请求。我想将此文档保存在我的couchdb中。
对于小文档,请求响应在很短的时间内返回,存储文档。当文档增长一点(仍然<~200k)时,响应需要很长时间,然后以超时返回。我将超时设置为120秒。
我错过了一些设置或编码错误吗?
- (void)post:(NSData*) requestBody {
startTime = [NSDate date];
NSURL* serverURL = [NSURL URLWithString: @"https://myUser:myPassword@myAcc.cloudant.com/myDB"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:serverURL];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
[request setTimeoutInterval:120.0];
[request setHTTPBody:requestBody];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if (response != nil) {
if ([response respondsToSelector:@selector(statusCode)])
{
int statusCode = [((NSHTTPURLResponse *)response) statusCode];
NSLog(@"StatusCode returned was %i", statusCode);
}
NSLog(@"Response: %@",response);
}
if ([data length] >0 && error == nil)
{
NSLog(@"data: %@", data);
// DO YOUR WORK HERE
}
else if ([data length] == 0 && error == nil)
{
NSLog(@"Nothing was downloaded.");
}
else if (error != nil){
NSLog(@"Error = %@", error);
}
}];
编辑:超时问题仍然存在。我在didSendBodyData中记录了进度并识别出发送的字节数。不是全部,然后超时发生。使用curl,上传工作正常。
此外,我在日志中认识到一件事:当请求成功时,总字节数和预期字节数是相同的:
Total Bytes written: 161120
Expected Bytes to write: 161120
When the request failed:
Total Bytes written: 163840
Expected Bytes to write: 166839
还有其他想法吗?
- (void)post:(NSData*) requestBody {
NSURL* serverURL = [NSURL URLWithString: @"https://mySpace.cloudant.com/myDb"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:serverURL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:requestBody];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
#pragma mark -
#pragma mark Connection Delegates
- (void) connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if ([challenge previousFailureCount] == 0) {
NSLog(@"received authentication challenge");
NSURLCredential *newCredential = [NSURLCredential credentialWithUser:@"myUser"
password:@"myPwd"
persistence:NSURLCredentialPersistenceForSession];
NSLog(@"credential created");
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
NSLog(@"responded to authentication challenge");
}
else {
NSLog(@"previous authentication failure");
}
}
答案 0 :(得分:0)
这似乎是网址格式的问题。使用低级HTTP库时,必须手动添加基本身份验证标头 - NSURLConnection and Basic HTTP Authentication in iOS显示如何执行此操作。超时可能是由于设备试图联系无效主机。
您可以通过尝试使用curl直接发出请求来测试这一点,即:
curl -XPOST https://username.password@username.cloudant.com/db -H 'Content-Type:application/json' -d @test.json
其中test.json包含超时的JSON。
使用curl可以更容易地进行调试(您将看到原始响应),并确认它是服务器端问题还是特定于库的问题。