2012-11-05 23 views
1

我一直在試用一段時間,使用Box 2.0 API從Objective C客戶端上傳文件到我的Box文件夾。我讀過從幾個帖子:使用目標C框文件上傳API

我使用Curl成功嘗試,如文檔中提到,但試圖創建時總能得到404一個NSMutableUrlRequest。 這是我的代碼:

NSURL *URL = [NSURL URLWithString:@"https://api.box.com/2.0/files/content"]; 
    urlRequest = [[NSMutableURLRequest alloc] 
        initWithURL:URL cachePolicy:NSURLRequestReloadIgnoringCacheData 
        timeoutInterval:30]; 
    [urlRequest setHTTPMethod:@"POST"]; 
    AppDelegate *appDelegate = [AppDelegate sharedDelegate]; 
    NSString *p = [NSString stringWithFormat:@"BoxAuth api_key=%@&auth_token=%@",API_KEY,appDelegate.boxAuthToken]; 
    [urlRequest setValue:p forHTTPHeaderField:@"Authorization"]; 
    [urlRequest setValue:@"multipart/form-data, boundary=AaB03x" forHTTPHeaderField:@"Content-Type"]; 

    NSString *postBody = @"--AaB03x" 
      @"content-disposition: form-data; name=\"filename\"; filename=\"test.txt\";" 
      @"folder_id=466838434" 
      @"Content-type: text/plain" 
      @"" 
      @"testing box api 2.0" 
      @"" 
      @"--AaB03x--"; 

    NSData *data = [postBody dataUsingEncoding:NSUTF8StringEncoding]; 
    [urlRequest setHTTPBody:data]; 
    [urlRequest setValue:[NSString stringWithFormat:@"%d",[data length]] forHTTPHeaderField:@"Content-Length"]; 

回答

0

使用http://allseeing-i.com/ASIHTTPRequest/

這使得處理多形式更容易!

+1

請不要在論壇帖子上發佈api_key和auth_tokens類似於發佈您的用戶名和密碼。我將建議您編輯您的評論,提取詳細信息,並在Box上使您的授權令牌無效。 – Peter

+0

忘記這個圖書館傢伙 - http://allseeing-i.com/%5Brequest_release%5D :) – h4cky

3

我看到您構建postBody的方式有幾個問題。在代碼中使用字符串文字之間的換行符簡單地連接它們。實際上,您需要有回車符和換行符來分隔HTTP正文的不同部分。此外,你將兩個表單元素都混合在一起。該文件和folder_id是兩個單獨的表單元素。你可以嘗試這樣的事情:

NSString *postBody = @"\r\n--AaB03x\r\n" 
         "Content-Disposition: form-data; filename=\"test.txt\"\r\n" 
         "Content-Type: text/plain\r\n\r\n" 
         "testing box api 2.0" 
         "\r\n--AaB03x\r\n" 
         "Content-Disposition: form-data; name=\"folder_id\";\r\n\r\n" 
         "0" 
         "\r\n--AaB03x--\r\n\r\n"; 

我認爲應該工作提供的一切都設置正確。