Alamofire 4得到了错误的请求

时间:2017-11-20 16:50:43

标签: swift get alamofire

我必须提出此请求

curl --request GET \
  --url http://site.exampleTest \
  --header 'authorization: longtoken'

所以我已经完成了这个功能:

    class func getRequest(endPoint: String, headers: [String : String], success:@escaping(JSON) -> Void,  failure:@escaping(NSError) -> Void) {

        Alamofire.request(myBaseURL + endPoint, headers: headers).responseJSON { (responseObject) in
            print(responseObject)

            if responseObject.result.isSuccess {
                let resJson = JSON(responseObject.result.value!)
                success(resJson)
            }
            if responseObject.result.isFailure {
                let error = responseObject.result.error!
                failure(error as NSError)
            }
        }

    }

我这样推出它:

let headerRequest = ["authorization":getUserDefaultElement(key: "token")]

    APIManager.getCurrentChatRequest(endPoint: "chats", headers: headerRequest, success: { (JSONObject) in
            print(JSONObject.debugDescription)
        }, failure: { (error)  in
            print(error)
        })
  

FAILURE:   responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(错误   Domain = NSCocoaErrorDomain Code = 3840“字符周围的值无效   0.“UserInfo = {NSDebugDescription =字符0周围的值无效。}))错误域= Alamofire.AFError代码= 4”JSON无法序列化   因为错误:无法读取数据,因为它不在   格式正确。“

同样的道理我在邮差上没有错误,所以我错在哪里?

修改

我得到的应该是这个

    {
      "data": [
        {
         stuff in here
         } 
       ]
    }  

编辑2

这是快速的方式,从邮递员中挑选,我得到200 OK:

let headers = [
  "authorization": "token" //modified by me
]

let request = NSMutableURLRequest(url: NSURL(string: "http://link.api.me")! as URL, //modified by me
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()

1 个答案:

答案 0 :(得分:1)

试一试。我相信你并没有把标题放在正确的格式中。

class func actualReq() {
    let headerRequest: HTTPHeaders = [
        "authorization":getUserDefaultElement(key: "token")
    ]

    APIManager.getCurrentChatRequest(endPoint: "chats", headers: headerRequest, success: { (JSONObject) in
        print(JSONObject.debugDescription)
    }, failure: { (error)  in
        print(error)
    })
}

class func getRequest(endPoint: String, headers:HTTPHeaders, success:@escaping(JSON) -> Void,  failure:@escaping(NSError) -> Void) {

    Alamofire.request(myBaseURL + endPoint, method: .get, headers: headers).responseJSON{ responseObject in
        switch response.result {
        case .success(let value):
            let swiftyJson = JSON(value)
            print(value)
            success(resJson)
        case .failure(let error):
            print("Error: \(error)")
            failure(error as NSError)

        }
    }
}

另一种方法:

Alamofire.request(myBaseURL + endPoint, method: .get, headers: headers).responseJSON{ responseObject in
        if response.response?.statusCode == 200 {
            print ("success")
        }else {
            guard let responseCode = response.response?.statusCode else {return}
            print ("code: \(responseCode)")
        }
    }
}