objective-c - 使用 https Amazon AWS 上传图像时出现证书错误

标签 objective-c swift amazon-web-services image-uploading

我在 Amazon AWS 中上传图像时遇到问题。这是我的代码:

import UIKit

protocol ContentUploaderDelegate {

    func onContentLoadComplete(status:Bool,serverResponse:String)
}


class ContentUploader
{
    let contentURL = "https:<MY URL>amazonaws.com/api/v1/contents"
    var delegate:ContentUploaderDelegate?


    func uploadImage(image:UIImage,xAuth:String,mimeType:String,imageName:String)
    {
        let url = NSURL(string: contentURL)

        let request = NSMutableURLRequest(URL: url!)
        request.HTTPMethod = "POST"

        let boundary = generateBoundaryString()

        //define the multipart request type
        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
        request.setValue(xAuth, forHTTPHeaderField: "x-auth-token")
        request.setValue("application/json", forHTTPHeaderField: "accept")

        let image_data = UIImageJPEGRepresentation(image, 1.0)

        if(image_data == nil)
        {
            return
        }

        let body = NSMutableData()

        //name to save in server
        let fname = imageName
        let mimetype = mimeType

        //define the data post parameter
        body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData("Content-Disposition:form-data; name=\"test\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData("hi\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData("Content-Disposition:form-data; name=\"files\"; filename=\"\(fname)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData("Content-Type: \(mimetype)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData(image_data!)
        body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        //set the HTTPBody
        request.HTTPBody = body

        let session = NSURLSession.sharedSession()

        let task = session.dataTaskWithRequest(request) {
            (
            let data, let response, let error) in

            guard let _:NSData = data, let _:NSURLResponse = response  where error == nil else {
                print("error")
                self.delegate?.onContentLoadComplete(false, serverResponse: (error?.description)!)
                return
            }

            let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("success \(dataString)")
            self.delegate?.onContentLoadComplete(true, serverResponse:dataString! as String)
        }

        task.resume()
    }

    private func generateBoundaryString() -> String
    {
        return "Boundary-\(NSUUID().UUIDString)"
    }

以下委托(delegate)方法永远不会被调用。可能是什么原因?

    func URLSession(session: NSURLSession,
                    task: NSURLSessionTask,
                    didReceiveChallenge challenge: NSURLAuthenticationChallenge,
                                        completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?)
        -> Void) {

        let protectionSpace = challenge.protectionSpace

        let theSender = challenge.sender

        if protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
            if (challenge.protectionSpace.host == "ec2-52-36-216-81.us-west-2.compute.amazonaws.com") {
                if let theTrust = protectionSpace.serverTrust{

                    let theCredential = NSURLCredential(trust: theTrust)

                    theSender!.useCredential(theCredential, forAuthenticationChallenge: challenge)

                    return
                }
            }
        }
        theSender!.performDefaultHandlingForAuthenticationChallenge!(challenge)

        return
    }
}

我收到以下错误。知道为什么会出现此错误吗?

Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “.amazonaws.com” which could put your confidential information at risk." UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9813, NSErrorPeerCertificateChainKey={type = immutable, count = 1, values = ( 0 : .com i: www..com> )}, NSUnderlyingError=0x7f9d42aedc10 {Error Domain=kCFErrorDomainCFNetwork Code=-1202 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, kCFStreamPropertySSLPeerTrust=, _kCFNetworkCFStreamSSLErrorOriginalValue=-9813, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9813, kCFStreamPropertySSLPeerCertificates={type = immutable, count = 1, values = ( 0 : .com i: www..com> )}}}, NSLocalizedDescription=The certificate for this server is invalid. You might be connecting to a server that is pretending to be “.amazonaws.com” which could put your confidential information at risk., NSErrorFailingURLKey=https://amazonaws.com/api/v1/contents, NSErrorFailingURLStringKey=https://.amazonaws.com/api/v1/contents, NSErrorClientCertificateStateKey=0}

最佳答案

Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “.amazonaws.com”

我认为通用名称有问题“.amazonaws.com”

NSErrorFailingURLKey=https://amazonaws.com/api/v1/contents,
NSErrorFailingURLStringKey=https://.amazonaws.com/api/v1/contents

错误消息中显示的 URL 似乎不是众所周知的端点。我希望在那里看到类似 https://ec2-2-2-2-2.compute-1.amazonaws.com 或其他完全合格的域名。

错误消息也证实了这一点。您正在连接主机,但证书上的名称不匹配。这就是假装为“.amazonaws.com”错误的原因。

确认正确的端点,以及您的代码如何形成完整的 URL。

The following delegate method never gets called. What could be the reason?

错误发生在调用函数之前。由于证书错误, session 从未建立。

关于objective-c - 使用 https Amazon AWS 上传图像时出现证书错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37857996/

相关文章:

ios - 无法订阅 pubnub channel (错误 107)

ios - 应用程序终止后,Microsoft Azure 清除 Cookie

ios - AVMutableComposition : small jump between video segments when playing

python - 如何配置 Amazon EC2 实例以支持 python 分析器?

python - 有没有一种方法可以监视导致 linux 中的 python 脚本程序关闭的原因?

ios - Dropbox iOS API - 简单问题/DBRestClient 问题

objective-c - 添加一个 NSOperationQueue 到一个 NSOperation

ios - 从多个 CloudKit 记录创建 MapKit Circle 覆盖

api - Swift 中的 Youtube API 到 AlamoFire

amazon-web-services - 如何在另一个模板中引用SSM参数