2 peterchen149 peterchen149 于 2015.05.26 19:06 提问

使用AFNetWorking 上传字符串,请求失败,Request failed: 请求太大
ios

我要把图片换成nsdata,然后再用base64encoding,把encoding后生成的字符串上传到
服务器,就出这个问题,
报错信息:err:Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: 请求太大 (413)"
我同事用的ASIHTTPRequest库就没问题,请问如何解决?
代码:

 UIImage *img = [self createThumbnailWithSourceImge:sourceImg andNewSize:sz];

       data  = UIImageJPEGRepresentation(img, 0.01);
        NSString *encodedSTR  = [data base64Encoding];
                NSString *currentUrl = @"/app/b/test";
        NSString *urlStr = [NSString stringWithFormat:@"%@%@?picStr=%@",BASEURL,currentUrl,encodedSTR];
        NSURL *url = [NSURL URLWithString:urlStr];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
                 AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc]initWithRequest:request];
    op.responseSerializer = [AFJSONResponseSerializer serializer];
    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSLog(@"success:%@",responseObject);
        successBlock(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        failureBlock(error);
    }];
    [op start];


     //   [manager POST:urlStr parameters:nil
     //         success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //          NSLog(@"success:%@",responseObject);
         //     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         //         NSLog(@"err:%@",error);
         //     }];

5个回答

qq_27361099
qq_27361099   2015.05.26 22:38

使用AFNetworking 2.0 请求数据时出现错误 Request failed: unacceptable content-type: text/html 解决方法

添加一行

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
即可

整个代码为:

复制代码
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
NSDictionary *parameters = @{@"foo":@"bar"};
[manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error:%@",error);
}];
复制代码

peterchen149
peterchen149 不是报“unacceptable content-type: text/html“,是”Request failed: request too large (413)“请求太大
接近 3 年之前 回复
ghf00123
ghf00123   2015.06.19 10:08
  • 这是NSURLSessionTask的一个bug. 用流处理下reuest请求就可以了。以下代码是解决Status Code: 411 (需要内容长度头 (Length required)的方法,可以参考下。

    // Prepare a temporary file to store the multipart request prior to sending it to the server due to an alleged
    // bug in NSURLSessionTask.
    NSString* tmpFilename = [NSString stringWithFormat:@"%f", [NSDate timeIntervalSinceReferenceDate]];
    NSURL* tmpFileUrl = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:tmpFilename]];
    
    AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
    
    // Create a multipart form request.
    NSMutableURLRequest *request = [requestSerializer multipartFormRequestWithMethod:@"POST" URLString:uploadUrl parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:path] name:name fileName:fileName mimeType:contentType error:nil];
    
    } error:nil];
    
    // Dump multipart request into the temporary file.
    [requestSerializer requestWithMultipartFormRequest:request writingStreamContentsToFile:tmpFileUrl completionHandler:^(NSError *error) {
    
        // Once the multipart form is serialized into a temporary file, we can initialize
        // the actual HTTP request using session manager.
    
        // Create default session manager.
        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer]; //很重要,去掉会出现Content-Type错误
    
        // Show progress.
        NSProgress *progress = nil;
    
        // Here note that we are submitting the initial multipart request. We are, however,
        // forcing the body stream to be read from the temporary file.
        NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:tmpFileUrl progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    
            // Cleanup: remove temporary file.
            [[NSFileManager defaultManager] removeItemAtURL:tmpFileUrl error:nil];
    
            // Do something with the result.
            if (error) {
    
                NSLog(@"upload Error: %@", error);
                result (nil,error);
    
            }else
            {
                NSDictionary *jsonValue = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:NULL];
                NSLog(@"upload Success: %@", jsonValue);
    
                result (jsonValue,error);
            }
        }];
    

// // Add the observer monitoring the upload progress.
// [progress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:NULL];

    // Start the file upload.
    [uploadTask resume];

[参考链接](https://github.com/AFNetworking/AFNetworking/issues/1398 "")
ghf00123
ghf00123 细看了楼主的问题,感觉和我的不一样,所以上述解决办法可能不太适合楼主,但可以参考一下。
接近 3 年之前 回复
qq_33480568
qq_33480568   2015.12.23 14:39

请问楼主最后是怎么解决的,我上传清晰点的图片就报Request failed: request too large (413)

Victor8910
Victor8910 你解决这个问题了嘛?
一年多之前 回复
ccshonger
ccshonger   2016.03.23 15:08

楼主怎么解决的啊

Victor8910
Victor8910 你解决这个问题了嘛?
一年多之前 回复
ccshonger
ccshonger   2016.03.23 15:08

楼主怎么解决的啊

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!