Objective-C Box 2.0文件上传 - 问题

时间:2012-07-19 15:24:40

标签: objective-c box-api

过去几天我一直在尝试使用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);

但是,我仍然得到了回报: { “类型”: “错误”, “状态”:404, “代码”: “NOT_FOUND”, “HELP_URL”: “http://developers.box.com/docs/#errors”, “消息”:“不发现”, “REQUEST_ID”: “10130600215xxxxxxxxxxx”}

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

1 个答案:

答案 0 :(得分:4)

修正了它。问题出在我的“边界”构造代码中。我有:

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

应该有:

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

发现错误的终止'\ r \ n'。那好吧。只浪费了大约4个小时。 : - )