我正在尝试将图片上传到API,然后使用结果。使用Postman时,一切都运行成功。当我使用导出功能将代码转换为Objective-C时,我尝试运行它,但我得到状态代码400(我的参数无效)。
这是我自己的代码:
// Get image name
NSURL *refURL = [info valueForKey:UIImagePickerControllerReferenceURL];
PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:@[refURL] options:nil];
NSString *filename = [[result firstObject] filename];
// Get image file path and append file name onto it
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:filename];
[imageData writeToFile:path atomically:YES];
NSDictionary *headers = @{ @"content-type": @"multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
@"Content-Type": @"multipart/form-data",
@"Accept": @"application/json",
@"Authorization": @"Token 60f6be2a21bdf731d86a8817b440a1afba692fed",
@"Cache-Control": @"no-cache",
@"Postman-Token": @"7d262730-0c7d-66dc-bbbb-43f40dbfe8ce" };
NSArray *parameters = @[ @{ @"name": @"task", @"value": @"dc9ef71a-b8a0-4a12-90fd-83d717cf887f" },
@{ @"name": @"image_file", @"fileName": path } ];
NSString *boundary = @"----WebKitFormBoundary7MA4YWxkTrZu0gW";
NSError *error;
NSMutableString *body = [NSMutableString string];
for (NSDictionary *param in parameters) {
[body appendFormat:@"--%@\r\n", boundary];
if (param[@"fileName"]) {
[body appendFormat:@"Content-Disposition:form-data; name=\"%@\"; filename=\"%@\"\r\n", param[@"name"], param[@"fileName"]];
[body appendFormat:@"Content-Type: %@\r\n\r\n", param[@"contentType"]];
[body appendFormat:@"%@", [NSString stringWithContentsOfFile:param[@"fileName"] encoding:NSASCIIStringEncoding error:&error]];
if (error) {
NSLog(@"%@", error);
}
} else {
[body appendFormat:@"Content-Disposition:form-data; name=\"%@\"\r\n\r\n", param[@"name"]];
[body appendFormat:@"%@", param[@"value"]];
}
}
[body appendFormat:@"\r\n--%@--\r\n", boundary];
NSData *postData = [body dataUsingEncoding:NSASCIIStringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://api.vize.ai/v1/classify/"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"%@", error);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(@"%@", httpResponse);
}
}];
[dataTask resume];
(这里没有显示,但我正在尝试使用用户从图像选择器中选择的图像。)为什么我得到状态代码400,我如何才能得到正确的结果?