HTTP POST请求发送图像
我试图通过HTTP POST请求将图像发布到web服务。
API文档说图像参数应该是“想要分析的图像的二进制文件数据 - 仅限于PNG,GIF,JPG”。
这是我试图使用的代码:
UIImage *image = [UIImage imageNamed:@"air.jpg"];
    NSData *imgData = UIImageJPEGRepresentation(image, 1.0);
    NSURLResponse *response;
    NSError *error = nil;
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://pictaculous.com/api/1.0/"]
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:60.0];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:imgData];
    NSData *receivedData = [NSURLConnection sendSynchronousRequest:request
                                                 returningResponse:&response
                                                             error:&error];
    if(error!=nil) {
        NSLog(@"web service error:%@",error);
    }
    else {
        if(receivedData !=nil) {
            NSError *Jerror = nil;
            NSDictionary* json =[NSJSONSerialization
                                 JSONObjectWithData:receivedData
                                 options:kNilOptions
                                 error:&Jerror];
            if(Jerror!=nil) {
                NSLog(@"json error:%@",Jerror);
            }
        }
    }
问题是,在JSON响应中,我总是收到错误“您必须提供图像”,就好像接收的图像格式不正确一样。
是不是“UIImageJPEGRepresentation”从图像获取二进制数据的正确方法?
有没有其他方法可以从我的JPEG图像获取二进制文件数据?
谢谢,科拉多
如果你想简化你的代码,你可以使用一个简单的NSURLConnection包装器,如STHTTPRequest。
STHTTPRequest *r = [STHTTPRequest requestWithURLString:@"http://pictaculous.com/api/1.0/"];
NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"jpg"];
NSData *data = [NSData dataWithContentsOfFile:path];
[r addDataToUpload:data parameterName:@"image"];
r.completionBlock = ^(NSDictionary *headers, NSString *body) {
    NSLog(@"-- %@", body);
};
r.errorBlock = ^(NSError *error) {
    NSLog(@"-- error: %@", error);
};
[r startAsynchronous];
上一篇: HTTP POST request to send an image
下一篇: Rails parameters are different when posting the same payload via Curl or Android
