AFNetworking 2-图像上传-请求失败:不支持的媒体类型(415) [英] AFNetworking 2 - Image upload - Request failed: unsupported media type (415)

查看:376
本文介绍了AFNetworking 2-图像上传-请求失败:不支持的媒体类型(415)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题已经被回答了多次,但是我尝试了所有的答案都没有运气。我不认为我从根本上做错了什么,但在这里肯定有错。

I know this question was answered multiple times, but I tried all the answers with no luck. I don't think that I do something fundamentally wrong but something goes definitely wrong here.

我使用以下代码将PNG文件上传到 tinypng.com 。据我所知,上传本身可以正常工作,但是我收到错误消息:请求失败:不支持的媒体类型(415)

I use the following code to upload PNG files to tinypng.com. As far as I can see the upload itself works, but I receive the error message: Request failed: unsupported media type (415)

我使用的图像以JPEG格式加载,然后调整大小并转换为PNG格式。保存的文件很好。现在,我想在将它们保存到光盘之前将它们发送到TinyPNG API。

The images I use are loaded as JPEG, then resized and transformed to PNG format. The saved files are fine. Now I want send them to the TinyPNG API before I save them to disc.

如果有人知道出了什么问题或有使用该服务的经验,请告诉我。
预先感谢!

If anyone has an idea whats wrong or has experience with that service, please let me know. Thanks in advance!

详细的错误消息

Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: unsupported media type (415)" 
UserInfo=0x6000000e4900 {
    com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x600000220200> { URL: https://api.tinypng.com/shrink } 
    { 
        status code: 415, headers {
            Connection = "keep-alive";
            "Content-Length" = 77;
            "Content-Type" = "application/json; charset=utf-8";
            Date = "Tue, 16 Dec 2014 20:24:16 GMT";
            Server = "Apache/2";
            "Strict-Transport-Security" = "max-age=31536000";
            "X-Powered-By" = "Voormedia (voormedia.com/jobs)";
        } 
    }, 
    NSErrorFailingURLKey=https://api.tinypng.com/shrink,
    com.alamofire.serialization.response.error.data=<7b226572 726f7222 3a224261 64536967 6e617475 
    7265222c 226d6573 73616765 223a2244 6f657320 6e6f7420 61707065 61722074 6f206265 20612050 
    4e47206f 72204a50 45472066 696c6522 7d>, 
    NSLocalizedDescription=Request failed: unsupported media type (415)
}

我使用的代码

-(void) uploadImage:(NSImage *)image {

    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:TINY_PNG_URL]];

    CGImageRef cgRef = [image CGImageForProposedRect:NULL
                                             context:nil
                                               hints:nil];
    NSBitmapImageRep *newRep = [[NSBitmapImageRep alloc] initWithCGImage:cgRef];
    [newRep setSize:[image size]];   // if you want the same resolution
    NSData *imageData = [newRep representationUsingType:NSPNGFileType properties:nil];

    NSDictionary *parameters = @{@"username": USERNAME, @"password" : PASSWORD};

    AFHTTPRequestOperation *operation = [manager POST:@"" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

        //append image
        [formData appendPartWithFileData:imageData
                                    name:@"filename"
                                fileName:@"photo.png"
                                mimeType:@"image/png"];

    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@ ***** %@", operation.responseString, error);
    }];

    [operation start];
} 


推荐答案

在Mattijs的支持下TinyPNG我已经开始工作了!谢谢Mattijs!

With the support of Mattijs from TinyPNG I've got it working! Thanks Mattijs!

问题是,TinyPNG API期望请求正文仅是图像数据,而多部分表单数据正文不是这种情况。

The problem was, that the TinyPNG API expects the request body to only be the image data, which isn't the case with the multipart form data body I used in my original code.

我的工作方案是:

-(void) uploadImage:(NSImage *)image {

    NSData *imageData = [self PNGRepresentationOfImage:image];

    NSURL *url = [NSURL URLWithString:TINY_PNG_URL];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:imageData];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"image/png" forHTTPHeaderField:@"Content-Type"];

    NSString *authStr = [NSString stringWithFormat:@"%@:%@", USERNAME, PASSWORD];
    NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
    NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]];
    [request setValue:authValue forHTTPHeaderField:@"Authorization"];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.responseSerializer = [AFJSONResponseSerializer serializer];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id result) {
        NSLog(@"Success: %@ ***** %@", operation.responseString, result);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@ ***** %@", operation.responseString, error);
    }];
    [operation start];
}

这篇关于AFNetworking 2-图像上传-请求失败:不支持的媒体类型(415)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆