1

我正在尝试使用 GCDWebServerFileResponse 将文件从一台设备发送到另一台设备,但每次都出现以下错误:

Optional(Error Domain=NSURLErrorDomain Code=-1017 "cannot parse response" UserInfo={NSUnderlyingError=0x14e6d46a0 {Error Domain=kCFErrorDomainCFNetwork Code=-1017 "(null)" UserInfo={_kCFStreamErrorCodeKey=-1, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=http://xx.xx.xx.xx:8080/course.json, NSErrorFailingURLKey=http://xx.xx.xx.xx:8080/course.json, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-1, NSLocalizedDescription=cannot parse response})

以下是我的 GET 请求代码:

func sendGetRequestToTeacher(data: AnyObject, IP: String, completionHandler: ((Bool, AnyObject) -> Void)? = nil) {
    let archivedData = NSKeyedArchiver.archivedDataWithRootObject(data)
    let url = NSURL(string: ("http://" + IP + ":\(self.port)/" + "course.json"))!
    let request = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 30.0)
    request.networkServiceType = NSURLRequestNetworkServiceType.NetworkServiceTypeVoIP
    request.HTTPMethod = "GET"
    request.HTTPBody = archivedData
    request.setValue("application/octet-stream", forHTTPHeaderField: "Accept")
    request.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
    request.setValue("\(archivedData.length)", forHTTPHeaderField: "Content-Length")

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, err) -> Void in
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            if let err = err {
                completionHandler?(false, err)
            } else if let data = data, let unarchivedData = NSKeyedUnarchiver.unarchiveObjectWithData(data) {
                completionHandler?(true, unarchivedData)
            }
        })
    })
    task.resume()
}

这是我的 GET 处理程序:

private func addDefaultHandlerForGetMethod() {
    self.server.addGETHandlerForBasePath("/", directoryPath: "/", indexFilename: nil, cacheAge: 3600, allowRangeRequests: true)
}

private func addHandlerForGetMethod() {
    self.server.addHandlerWithMatchBlock({ (requestMethod, requestURL, requestHeaders, urlPath, urlQuery) in
        if requestMethod != "GET" {
            return nil
        }
        if !urlPath.hasSuffix("/course.json") {
            return nil
        }
        return GCDWebServerRequest(method: requestMethod, url: requestURL, headers: requestHeaders, path: urlPath, query: urlQuery)
        }, processBlock: { (request) in
            let filePath = STCCourseManager.sharedInstance.coursesFolderPath.stringByAppendingPathComponent((STCCourseManager.sharedInstance.currentCourseID?.stringByAppendingPathComponent(request.path.stringByRemovingPercentEncoding!))!)
            do {
                let fileAttributes = try NSFileManager.defaultManager().attributesOfItemAtPath(filePath)
                if let fileType = fileAttributes[NSFileType] as? String where fileType == NSFileTypeRegular {
                    let response = GCDWebServerFileResponse(file: filePath, byteRange: request.byteRange)
                    response.setValue("bytes", forAdditionalHeader: "Accept-Ranges")
                    response.cacheControlMaxAge = 3600
                    return response
                }
            } catch {
                print("\(error)")
            }
            return GCDWebServerResponse(statusCode: GCDWebServerClientErrorHTTPStatusCode.HTTPStatusCode_NotFound.rawValue)
    })

另外,我刚刚意识到,如果我使用 curl -v http://127.0.0.1:8080/fileURL,则请求由 defaultHandlerForGet 处理,并在终端中正确返回文件,但是我的自定义处理程序返回“未找到” . 我的自定义处理程序中缺少什么?

我真的很感激在解决这个问题方面的任何帮助。

4

1 回答 1

0

我能够通过将我的请求更改为以下内容来解决此问题:

    let url = NSURL(string: ("http://" + IP + ":\(self.port)/" + "distribution"))!
    let request = NSMutableURLRequest(URL: url)
    request.timeoutInterval = 30.0

不确定之前的请求大腿有什么问题。可能是我的某些标头字段设置不正确。由于缺乏任何答案,我接受了这个解决方案。

于 2016-02-04T00:56:57.143 回答