【问题标题】:Issue with NSURLSession and Content-TypeNSURLSession 和 Content-Type 的问题
【发布时间】:2026-01-16 07:25:02
【问题描述】:

我正在尝试将照片上传到网络服务,我正在使用以下代码:

NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:imageToUpload], 0.5);

// 1
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.HTTPMaximumConnectionsPerHost = 1;
[config setHTTPAdditionalHeaders:@{@"Content-Type":@"multipart/form-data"}];

// 2
NSURLSession *upLoadSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];

// for now just create a random file name, dropbox will handle it if we overwrite a file and create a new name..
NSString *urlString =[NSString stringWithFormat:@"https://ABC.co.uk/photos?api_key=MYAPIKEY" ];
NSURL *webUrl = [NSURL URLWithString:urlString];


NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:webUrl];
[request setHTTPMethod:@"POST"];

// 3
NSURLSessionUploadTask *uploadTask = [upLoadSession uploadTaskWithRequest:request fromData:imageData];

// 4
//    uploadView.hidden = NO;
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

// 5
[uploadTask resume];

我收到错误 500,但我不知道该怎么办。

我尝试过实现 AFNetworking,如 ThisThisThis 之类的附加正文数据。然而,没有运气。

以上代码来自 Ray Wenderlich 的网站:Here

我需要提供的服务器是这样的:

  1. 文件(图片)
  2. API 密钥(我尝试使用 NSMutableURLRequest 的 addValue:forHTTPHeaderField: 但它不起作用,所以我在 URL 中使用它。我知道这不是安全方面的最佳做法,但我知道了绝望,因为我已经为此工作了 10 多个小时!一步一步!)
  3. Content-Type 变为 multipart/form-data

这就是我需要提供的全部内容,但我却一无所获!

有人可以帮忙吗?

提前谢谢你

更新 1:所以我对 URL 结构进行了一些更改,并将 API 密钥作为字典添加到 HTTPBody 中,现在我收到错误 403。

苹果没有做出任何努力来序列化这部分连接,这似乎真的很奇怪。反正。我真的很感谢任何人的帮助!

【问题讨论】:

    标签: ios post https nsurlsession nsurlsessionuploadtask


    【解决方案1】:

    尝试在请求中也设置Content-Type

    [request addValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
    

    【讨论】: