0

这里需要帮助,我正在尝试将文件上传到安全 API,我能够使用 Advanced REST Client chrome 扩展成功上传,但是当我尝试将其转换为 afnetworking 发布请求时,它总是返回请求超时错误,我已经这样做了 3 天,但我总是收到请求超时错误,尝试延长超时间隔但无济于事。

我的代码:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

[[CookieHandler sharedManager] cookieEaterUsingCookiesInURL:OC_BASE_URL];
NSString *csrftoken = [[CookieHandler sharedManager] getCSRFToken];

[manager.requestSerializer setValue:csrftoken forHTTPHeaderField:COOKIES_CSRFTOKEN_KEY];
[manager.requestSerializer setTimeoutInterval:120];

AFHTTPRequestOperation *operation = [manager POST:[self composeFullUrlWithRestApi:uploadUrl] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileData:fileData name:@"fileUpload" fileName:documentName mimeType:mimeType];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

[operation setUploadProgressBlock:^(NSUInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {
    NSLog(@"Wrote %ld/%ld", (long)totalBytesWritten, (long)totalBytesExpectedToWrite);
}];

打印operation变量产量:

<AFHTTPRequestOperation: 0x15731040, state: isExecuting, cancelled: NO request: <NSMutableURLRequest: 0x15523180> { URL: https://preprod.myUrl.com/uploadApi, headers: {
    "Accept-Language" = "en;q=1";
    CSRFToken = "cfbaf91f-6f2b-4ed1-a094-06c8eec6f757";
    "Content-Length" = 32943;
    "Content-Type" = "multipart/form-data; boundary=Boundary+B7082B5EB6A9063A";
    "User-Agent" = "ObjectiveConnect/5 (iPhone; iOS 8.0.2; Scale/2.00)";
} }, response: (null)>

打印错误产生:

Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." 
UserInfo=0x1561fec0 {NSErrorFailingURLStringKey=https://preprod.myUrl.com/uploadApi, 
NSErrorFailingURLKey=https://preprod.myUrl.com/uploadApi, 
NSLocalizedDescription=The request timed out., NSUnderlyingError=0x1567c400 "The request timed out."}
4

1 回答 1

0

基于此:相关的stackoverflow帖子

我应该提一下,这可能是服务器缺乏支持 AFNetworking 请求,或者该请求无法与所有服务器一起使用。

所以基于这个概念,我继续手动创建请求,幸运的是,该帖子的答案也提供了,所以这是我的版本:

typedef void (^uploadFileCompletionBlock)(NSURLResponse *response, id responseObject, NSError *error);
- (NSMutableURLRequest *)buildRequestWithUrl:(NSString *)url
                                withFileData:(NSData *)paramData
                                    fileName:(NSString *)name
                             fileContentType:(NSString *)fileContentType
{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:[self composeFullUrlWithRestApi:url]]];
    [request setHTTPMethod:@"POST"];

    [[CookieHandler sharedManager] cookieEaterUsingCookiesInURL:OC_BASE_URL];

    NSString *csrftoken = [[CookieHandler sharedManager] getCSRFToken];

    [request setValue:csrftoken forHTTPHeaderField:COOKIES_CSRFTOKEN_KEY];

    NSString *boundary = @"0xKhTmLbOuNdArY";
    NSString *endBoundary = [NSString stringWithFormat:@"\r\n--%@--", boundary];

    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    [request setValue:@"*/*" forHTTPHeaderField:@"Accept"];
    NSMutableData *tempPostData = [NSMutableData data];
    [tempPostData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    // Sample file to send as data
    [tempPostData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"\r\n", name] dataUsingEncoding:NSUTF8StringEncoding]];
    [tempPostData appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", fileContentType] dataUsingEncoding:NSUTF8StringEncoding]];
    [tempPostData appendData:paramData];
    [tempPostData appendData:[endBoundary dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:tempPostData];

    return request;
}

- (void) uploadFileWithFileData:(NSData *)fileData
                andDocumentName:(NSString *)documentName
                fileContentType:(NSString *)mimeType
                      uploadUrl:(NSString *)uploadUrl
             andCompletionBlock:(uploadFileCompletionBlock)completionBlock
{
    NSMutableURLRequest* request = [self buildRequestWithUrl:uploadUrl withFileData:fileData fileName:documentName fileContentType:mimeType];

    [NSURLConnection sendAsynchronousRequest:request queue:[[AFHTTPRequestOperationManager manager] operationQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        completionBlock(response, data, connectionError);
    }];
}

TL;博士

如果您的 AFNetworking 请求失败,请执行手动请求构建方式,您需要了解一些关于请求标头的知识才能理解这一点。

于 2015-11-26T10:51:42.583 回答