创建多部分正文请求swift

时间:2016-03-02 02:34:20

标签: ios swift nsurlsession nsurlrequest

我正在尝试使用NSURLSession创建一个多部分请求,但我无法获得可解码的请求。我在这里看到了几乎所有帖子,这段代码是几个帖子的组合。

/// Create custom OAuth2Request Measurement request.
    /// - Parameter data: Data to be sent.
    /// - Returns: NSMutableURLRequest
    internal func createOAuth2MeasurementPOSTRequest(f_fileData: NSData, f_fileName: String) -> NSMutableURLRequest {

        //Request Data
        let data = NSMutableData()

        // Create URL
        let target_URL = NSURL(string: target_URL_string)

        let req = OAuthManager.sharedInstance.oauth2.request(forURL:target_URL!)

        // Set method to POST
        req.HTTPMethod = "POST"

        // ignore cacheing
        req.cachePolicy = .ReloadIgnoringLocalCacheData

//        let boundary = generateBoundaryString()
//        let contentType = "multipart/form-data; boundary=\(boundary)"
//        req.setValue(contentType, forHTTPHeaderField:"Content-Type")


        // Get id
        if let tenID = NSUserDefaults.standardUserDefaults().objectForKey(Constants.TENANT_ID) {
//            // Append disposition data
//            let tenantLocationDictionary:[String:String] = [
//                "TenantId": tenID as! String,
//                // location ID needs to be dynamic
//                "LocationId": "7688f946-a558-49db-9477-098e073ad514"
//            ]

            let boundry:String = generateBoundaryString()
            let MPboundary:String = "\(boundry)"
            let endMPboundary:String = "\(MPboundary)"
            let data:NSData = f_fileData
            let body:NSMutableString = NSMutableString();

            let content:String = "multipart/form-data; boundary=\(boundry)"
            req.setValue(content, forHTTPHeaderField: "Content-Type")

            body.appendFormat("\(MPboundary)\r\n")
            body.appendFormat("Content-Disposition: form-data; name=\"moldel")
            body.appendFormat("{\"TenantId\": \"\(tenID)", "LocationId\":\"7688f946-a558-49db-9477-098e073ad514\"}\r\n")
            let end:String = "\(endMPboundary)"
            body.appendFormat("Content-Disposition: form-data; name=\"\(f_fileName)\"; filename=\"(f_fileName)\"\"\r\n")
            body.appendFormat("Content-Type: text/xml\r\n\r\n")
            let myRequestData:NSMutableData = NSMutableData();
            myRequestData.appendData(body.dataUsingEncoding(NSUTF8StringEncoding)!)
            myRequestData.appendData(data)
            myRequestData.appendData(end.dataUsingEncoding(NSUTF8StringEncoding)!)
            req.setValue("\(myRequestData.length)", forHTTPHeaderField: "Content-Length")
            req.HTTPBody = myRequestData
            req.HTTPMethod = "POST"
        }

        // append filedata
        data.appendData(f_fileData)

        // Add Data to body
        req.HTTPBody = data

        return req
    }

    /// Creates a GET request and returns it.
    /// - Parameter None:
    /// - Returns: NSMutableURLRequest
    internal func createOAuth2GETRequest() -> NSMutableURLRequest {
        // Create URL
        let target_URL = NSURL(string: target_URL_string)

        // Create mutable request
        let req = OAuthManager.sharedInstance.oauth2.request(forURL: target_URL!)

        // ignore cacheing
        req.cachePolicy = .ReloadIgnoringLocalCacheData

        // Return the request.
        return req
    }

我的边界应该包含一个包含tenantId和LocationId的字典。这是一篇用不同语言制作的成功帖子。

Content-Type: multipart/form-data; boundary=----WebKitFormBoundary1qyYAqC05he9W5sq
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Cookie: <cookie>
------WebKitFormBoundary1qyYAqC05he9W5sq
Content-Disposition: form-data; name="model"
{"TenantId": "7688f946-a558-49db-9477-098e073ad514", "LocationId":"7688f946-a558-49db-9477-098e073ad514"}
------WebKitFormBoundary1qyYAqC05he9W5sq
Content-Disposition: form-data; name="files"; filename="LOG0.XML"
Content-Type: text/xml
// Start of file
<?xml version="1.0" encoding="UTF-16"?>
... file continues

如何在Swift中复制此调用?

1 个答案:

答案 0 :(得分:0)

原始请求对我来说不对。主标题AFAIK后面应该有一个空行。

话虽如此,我看到的主要问题是,每次将边界插入文件时,都会丢失两个连字符。例如,如果将Content-Type中的边界设置为“foo”,则只要实际使用边界,就使用“--foo”。