簡體   English   中英

使用https Amazon AWS上傳圖像時出現證書錯誤

[英]Getting certificate error in Uploading image with https Amazon AWS

在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)"
    }

以下委托方法永遠不會被調用。 可能是什么原因?

    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
    }
}

我收到以下錯誤。 知道為什么會收到此錯誤嗎?

錯誤域= NSURLErrorDomain代碼= -1202“此服務器的證書無效。您可能正在連接到假裝為“ .amazonaws.com”的服務器,這可能會使您的機密信息受到威脅。 UserInfo = {NSURLErrorFailingURLPeerTrustErrorKey =,NSLocalizedRecoverySuggestion =是否仍要連接到服務器嗎?,_kCFStreamErrorDomainKey = 3,_kCFStreamErrorCodeKey = -9813,NSErrorPeerCertificateChainKey = {type =不可變,count = 1,值=(0:。 .com>)},NSUnderlyingError = 0x7f9d42aedc10 {Error Domain = kCFErrorDomainCFNetwork Code = -1202“(null)” UserInfo = {_ kCFStreamPropertySSLClientCertificateState = 0,kCFStreamPropertySSLPeerTrust =,_kCFNetworkCFCFertSSLErrorOriginalValue = -9813,關鍵代碼= Stream,PropertyValue = -9813,類型=不可變,計數= 1,值=(0:.com i:www..com>)}}},NSLocalizedDescription =此服務器的證書無效。 您可能正在連接到假裝為“ .amazonaws.com”的服務器,這可能會使您的機密信息受到威脅。,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或其他完全合格域名的內容。

錯誤消息也確認了這一點。 您正在連接主機,但是證書上的名稱不匹配。 這就是pretending to be “.amazonaws.com”錯誤的原因。

確認正確的端點,以及您的代碼如何形成完整的URL。

以下委托方法永遠不會被調用。 可能是什么原因?

該錯誤在調用函數之前發生。 由於證書錯誤,從未建立會話。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM