API未返回原始数据的有效响应。但在邮递员身上运作良好

时间:2015-04-23 10:44:40

标签: ios xcode swift

我正试图从服务器获取json响应,但收到我在下面粘贴的错误。但是api调用在postman上运行正常。请问你能解决我在这里做错了吗

  

可选(错误域= NSURLErrorDomain代码= -1012"操作无法完成。(NSURLErrorDomain错误-1012。)" UserInfo = 0x7f9050e1f750 {NSErrorFailingURLStringKey = https://rainforestcloud.com:9445/cgi-bin/post_manager,NSUnderlyingError = 0x7f9050fe4eb0"操作无法完成。(kCFErrorDomainCFNetwork错误-1012。)",NSErrorFailingURLKey = https://rainforestcloud.com:9445/cgi-bin/post_manager})

以下是我的代码片段

var theRequest : NSMutableURLRequest =  NSMutableURLRequest(URL: NSURL(string: base_url)!)
    theRequest.HTTPMethod = "POST"
    theRequest.setValue("text/html", forHTTPHeaderField: "Content-Type")
    theRequest.addValue("Cloud-ID", forHTTPHeaderField: "001226")
    theRequest.addValue("User", forHTTPHeaderField: "john.lee@rainforestautomation.com")
    theRequest.addValue("Password", forHTTPHeaderField: "rainforest")
    var stringData =  "confirm_message";
    var requestBodyData = stringData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
    theRequest.HTTPBody = requestBodyData;
    var response: NSURLResponse?
    var error: NSError?
    let urlData = NSURLConnection.sendSynchronousRequest(theRequest, returningResponse: &response, error: &error)
    if ((error) != nil)
    {
        println(error)

    }
    else
    {
        self.performSegueWithIdentifier("MeterView", sender: self)
    }
    theRequest.timeoutInterval = 0.20

postman api call images here Response image

2 个答案:

答案 0 :(得分:0)

我有这个代码连接到Rest api。它使用JSONValue,因为我假设返回的值是JSON。

调用它的方法是

dataFromServer('file.php', ["parm1": "value1", "parm2": 2])

func dataFromServer(file:String, var parms:Dictionary<String, AnyObject!>) -> JSONValue {


    let url = "\(SERVERURL)/\(file)"

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

    let boundary = "---------------------------29839217397249927731321937129879827"
    let contentType = "multipart/form-data; boundary=\(boundary)"

    request.addValue(contentType, forHTTPHeaderField: "Content-Type")

    let body = NSMutableData()

    for (key, value) in parms {

        if value is UIImage {
            //If uiimage

            if let img = value as? UIImage {

                var newWidth = 0
                var newHeight = 0
                var sizeLimit = 700 //in px

                let originalWidth = Int(img.size.width)
                let originalHeight = Int(img.size.height)

                //Get new size with max w/h = 700
                if originalWidth > originalHeight {
                    //Max width
                    newWidth = sizeLimit
                    newHeight = (originalHeight*sizeLimit)/originalWidth
                }else{
                    newWidth = (originalWidth*sizeLimit)/originalHeight
                    newHeight = sizeLimit
                }

                let newSize = CGSizeMake(CGFloat(newWidth), CGFloat(newHeight))
                UIGraphicsBeginImageContext(newSize)
                img.drawInRect(CGRectMake(0, 0, CGFloat(newWidth), CGFloat(newHeight)))
                let newImg = UIGraphicsGetImageFromCurrentImageContext()
                UIGraphicsEndImageContext()
                let imageData = UIImagePNGRepresentation(newImg)

                body.appendData(("\r\n--\(boundary)\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
                body.appendData(("Content-Disposition: form-data; name=\"\(key)\"; filename=\"tempImage.png\"\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
                body.appendData(("Content-Type: application/octet-stream\r\n\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
                body.appendData(NSData(data: imageData))
            }


        }else{

            body.appendData(("\r\n--\(boundary)\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
            body.appendData(("Content-Disposition: form-data; name=\"\(key)\";" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
            body.appendData(("\r\n\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
            body.appendData(("\(value)" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
        }
    }

    body.appendData(("\r\n--\(boundary)\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)

    request.HTTPBody = body

    var urlData:NSData?
    var response: NSURLResponse?
    var error: NSError?
    urlData = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)


    if let serverData = urlData {
        if let data = response {
            let aStr = NSString(data: serverData, encoding: NSUTF8StringEncoding)
            let json = JSONValue(urlData)
            println("Return \(file): \(aStr)")
            return json
        }
    }

    return JSONValue("")
}

我希望它有所帮助

答案 1 :(得分:0)

theRequest.addValue(“Cloud-ID”,forHTTPHeaderField:“001226”)

我这个请求我是以错误的方式插入值,我必须将值“Cloud-ID”与“001226”互换后,现在我的json响应工作正常并且完美...谢谢。

交换后

变为

theRequest.addValue(“001226”,forHTTPHeaderField:“Cloud-ID”)