gpt4 book ai didi

ios - NSURLRequest 导致 500 错误

转载 作者:行者123 更新时间:2023-11-29 10:44:40 25 4
gpt4 key购买 nike

我正在尝试使用 NSURL 请求进行 api 调用以上传图像,但我继续收到 500 错误。为了向您展示我在这里试图完成的是 curl 命令的样子。

$ curl -i -F api_password=<YOUR_API_PASSWORD> -F file=@<LOCAL_FILE_PATH> https://upload.api.com/

这是我目前所拥有的,我继续收到 500 个错误。你们能告诉我我做错了什么吗(我不是 NSURLRequest 大师)。

NSString *apiPass = @"apiKey";
NSString *filePath = imagePath;

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"https://upload.wistia.com"]];
[request setHTTPMethod:@"POST"];

NSString *contentType = [NSString stringWithFormat:@"multipart/form-data;"];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

// Create data string
NSString *dataString = [NSString stringWithFormat:@"api_password=%@&file=@%@", apiPass, filePath];

NSData *postData = [dataString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

[request setHTTPBody:[dataString dataUsingEncoding:NSUTF8StringEncoding]];

NSURLResponse * response = nil;
NSError * error = nil;

[NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];

最佳答案

尝试像这样编写您的 POST 请求:

NSString *boundary = @"---###-----##----##--#----###---BOUNDARY---###";
NSMutableData *postBody = [NSMutableData data];
NSString *postString = nil;

postString = [NSString stringWithFormat:@"\r\n--%@\r\n", boundary];
postString = [postString stringByAppendingString:@"Content-Disposition: form-data; name=\"api_password\"\r\n\r\n"];
postString = [postString stringByAppendingString:apiPass];

postString = [postString stringByAppendingString:[NSString stringWithFormat:@"\r\n--%@\r\n", boundary]];
postString = [postString stringByAppendingString:@"Content-Disposition: form-data; name=\"file\"\r\n\r\n"];
postString = [postString stringByAppendingString:filePath];

postString = [postString stringByAppendingString:[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary]];

[postBody appendData:[postString dataUsingEncoding:NSUTF8StringEncoding]];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://upload.wistia.com"]
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:60.0f];
[request setHTTPMethod:@"POST"];

[request setValue:@"*/*" forHTTPHeaderField:@"Accept"];
[request setValue:[@"multipart/form-data; boundary=" stringByAppendingString:boundary] forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", postBody.length] forHTTPHeaderField:@"Content-Length"];

[request setHTTPBody:postBody];

关于ios - NSURLRequest 导致 500 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22792849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com