HTTP POST request to send an image

I'm trying to post an image to a webservice by means of an HTTP POST request.

The API doc says that image parameter should be the "binary file data for the image you would like analyzed - PNG, GIF, JPG only."

This is the code I'm trying to use:

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);
            }
        }
    }

The problem is that in the JSON response I always receive the error "You must provide an image" as if the format of the received image was not correct.

Isn't "UIImageJPEGRepresentation" the correct way to get binary data from an image ?

Is there any other way I can get the binary file data from my JPEG image ?

Thanks, Corrado


如果你想简化你的代码,你可以使用一个简单的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://www.djcxy.com/p/48786.html

上一篇: 在Java中通过REST调用发布和检索JSON对象

下一篇: HTTP POST请求发送图像