使用NSURLSession / Swift 2.0

时间:2016-10-13 15:15:10

标签: swift rest curl nsurlsession box

我想将iOS应用程序中的日志文件直接上传到Box.com上的文件夹。阅读Box的api此功能随REST webservices一起提供。 api中的示例是cURL,终端开箱即用(抱歉,没有双关语)。

我们的应用程序是基于Swift的,我使用NSURLSession来发出请求。经过多次尝试计算,并仔细检查有关此主题的博客(iOS / Box)后,我仍未设法上传测试文件。

令人沮丧的是,api似乎是错误的,如here所示,但遵循此答案中建议的格式并没有帮助。

以下是我最近一次尝试的NSURLSession请求代码:

let path = NSBundle.mainBundle().pathForResource("testFile", ofType: "txt")
let data: NSData? = NSData(contentsOfFile: path!)

let url = NSURL(string: "https://upload.box.com/api/2.0/files/content")!
let request = NSMutableURLRequest(URL: url)

let boundary = generateBoundaryString()
request.HTTPMethod = "POST"
request.addValue("Bearer q1ckXDSTC0EcsCJiLtW638o5x5roWabb", forHTTPHeaderField: "Authorization")

let body = NSMutableData()
body.appendData("Content-Type: multipart/form-data; boundary=\(boundary)\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("--\(boundary)\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition: form-data; name=\"parent_id\"\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Type: text/plain\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("0\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("--\(boundary)\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition: form-data; name=\"filename\"; filename=\"testFile.txt\"\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Type: text/plain\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(data!)
body.appendData("\n--\(boundary)--".dataUsingEncoding(NSUTF8StringEncoding)!)
request.HTTPBody = body

let task = NSURLSession.sharedSession().uploadTaskWithRequest(request, fromData: data!, completionHandler:  {(data,response,error) in
    if(error != nil) {
        NSLog("Error message = \(error.debugDescription)")
    }
    if(response != nil) {
        NSLog("Response = \(response)")
    }
    if(data != nil) {
        NSLog("Data = \(data!)")
    }
});
task.resume()

服务器响应405错误。

Response = Optional(<NSHTTPURLResponse: 0x157de26d0> { URL: https://upload.box.com/api/2.0/files/content } { status code: 405, headers {
    Age = 0;
    Allow = "GET, OPTIONS, HEAD";
    Connection = "keep-alive";
    "Content-Length" = 0;
    "Content-Type" = "text/html; charset=UTF-8";
    Date = "Thu, 13 Oct 2016 14:49:49 GMT";
    Server = ATS;
} })

从上面的例子中,请求标题是:

Request headers - Optional(["Authorization": "Bearer q1ckXDSTC0EcsCJiLtW638o5x5roWabb"])!

请求正文是:

body - Content-Type: multipart/form-data; boundary=0B1D5883-9EA6-4D6B-9FEC-C51D817D5975
--0B1D5883-9EA6-4D6B-9FEC-C51D817D5975
Content-Disposition: form-data; name="parent_id"
Content-Type: text/plain
0
--0B1D5883-9EA6-4D6B-9FEC-C51D817D5975
Content-Disposition: form-data; name="filename"; filename="testFile.txt"
Content-Type: text/plain
Hello
--0B1D5883-9EA6-4D6B-9FEC-C51D817D5975--

我们已尝试使用Wireshark传播cURL请求,但因为它是SSL请求,所以这没有多大帮助。

cURL请求的详细版本如下所示:

0000: POST /api/2.0/files/content HTTP/1.1
0026: Host: upload.box.com
003c: User-Agent: curl/7.47.0
0055: Accept: */*
0062: Authorization: Bearer o6ojjxpfECdKrBzIUhiRyRKHTTXg8Sll
009a: Content-Length: 368
00af: Expect: 100-continue
00c5: Content-Type: multipart/form-data; boundary=--------------------
0105: ----ed667cff7b6570a1
011b: 
== Info: Done waiting for 100-continue
=> Send data, 285 bytes (0x11d)
0000: --------------------------ed667cff7b6570a1
002c: Content-Disposition: form-data; name="attributes"
005f: 
0061: {"name":"testFile.txt", "parent":{"id":"0"}}
008f: --------------------------ed667cff7b6570a1
00bb: Content-Disposition: form-data; name="file"; filename="testFile.
00fb: txt"
0101: Content-Type: text/plain
011b: 
=> Send data, 35 bytes (0x23)
0000: This is a test file.
=> Send data, 48 bytes (0x30)
0000: 
0002: --------------------------ed667cff7b6570a1-- 

我们也试图完全复制,但问题仍然存在。

如果有人成功实现了这一点,我将非常感谢一些方向或建议

我们联系了Box支持团队,但他们还没有回复。

0 个答案:

没有答案