3

在过去的几天里,我一直在尝试使用 Box 进行文件上传。我知道我做错了什么,但就是看不到它是什么。

我已经尽可能地减少了我的代码,就这样:

// Configure the request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"https://api.box.com/2.0/files/data"]];
[request setHTTPMethod:@"POST"];

[request setValue:boxAuthString forHTTPHeaderField:@"Authorization"];

// Setu up the request
NSString *boundary = [NSString stringWithString:@"--PLEASEHELPMEGETTHISWORKING"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@\r\n",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

NSMutableData *body = [NSMutableData data];

// Add the info and data for the file.
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Disposition:form-data;name=\"filename\";filename=\"testfile.txt\"\r\n"]
                      dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type:text/plain\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Hello"] dataUsingEncoding:NSUTF8StringEncoding]];

// Add the info and data for the target folder. 
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Disposition:form-data;name=\"folder_id\"\r\n\r\n"]
                  dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"0"] dataUsingEncoding:NSASCIIStringEncoding]];  

// Close the body and set to the request
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding: NSUTF8StringEncoding]];
[request setHTTPBody:body];    

// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

NSLog(@"%@", returnString);

但是,我仍然得到返回: {"type":"error","status":404,"code":"not_found","help_url":"http://developers.box.com/docs/#错误","消息":"未找到","re​​quest_id":"10130600215xxxxxxxxxxx"}

请有人帮我指出正确的方向,因为当我使用 POSTMAN 或 cURL 时,我可以让它工作 - 所以这显然是我的代码的问题。我怀疑这与“folder_id”有关,但似乎无法诊断出真正的原因。

4

1 回答 1

4

解决它。问题出在我的“边界”构造代码中。我得到了:

NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@\r\n",boundary];

并且应该有:

NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];

找出不正确的终止“\r\n”。那好吧。只浪费了大约4个小时。:-)

于 2012-07-19T19:37:02.633 回答