带有发布请求的NSURLSession序列化错误

时间:2016-06-06 06:32:16

标签: ios swift nsurlsession instagram-api nsjsonserialization

我正在尝试获取Instagram的访问令牌,但却经常出现错误$ . upip-func.sh $ upip www.google.com server: www.google.com, trial 1 $ echo $? 0 $ upip ping.google.com server: ping.google.com, trial 1 bash: ping.google.com is down: checking again after 1 sec server: ping.google.com, trial 2 2016-06-06 00:35:18: Server ping.google.com is DOWN $ echo $? 1 $ if upip www.google.com; then echo OK; else echo Fail; fi server: www.google.com, trial 1 OK $ if upip ping.google.com; then echo OK; else echo Fail; fi server: ping.google.com, trial 1 bash: ping.google.com is down: checking again after 1 sec server: ping.google.com, trial 2 2016-06-06 00:38:32: Server ping.google.com is DOWN Fail $ 我认为这是一个序列化问题,因为我的参数没有正确序列化。 我在You must provide client id上尝试了它并且效果很好,但在POSTMAN上它会抛出错误。

错误

NSURLSession

在序列化时我在做错了什么。

{
    code = 400;
    "error_message" = "You must provide a client_id";
    "error_type" = OAuthException;
}

我也试过这个

let instaInfoDict = NSDictionary(objects: ["client_id","client_secret","grant_type","redirect_uri","code"], forKeys: [kCLientIdInstagram,kCLientSecretIdInstagram,"authorization_code",kRedirectUriInstagram,code])
// Hit post request with params
WebServices().postRequest(kAccessTokenGenerationInstagram, bodyData: instaInfoDict, completionBlock: { (responseData) in
                print(responseData)

})


//WEBSERVICE CLASS:

 func postRequest(url:String, bodyData:NSDictionary, completionBlock:WSCompletionBlock){
        if let url = NSURL(string: url){
            let headers = [
                "Accept": "application/json",
                "content-type": "application/json"]

            let session = NSURLSession.sharedSession()

            let request = NSMutableURLRequest(URL: url, cachePolicy: .UseProtocolCachePolicy, timeoutInterval: 10)
            request.HTTPMethod = "POST"
            request.allHTTPHeaderFields = headers

            request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(bodyData, options: [.PrettyPrinted])

            let task =  session.dataTaskWithRequest(request, completionHandler: { (data, response, error) in
       if error != nil {
            // Handle error


            completionBlock!(responseData:nil)
        }
        else{
//Parsing the data
            let parsedData = parseJson(response as? NSData)

            completionBlock!(responseData: parsedData)

        }

            })

            task.resume()
        }


    }

1 个答案:

答案 0 :(得分:2)

似乎问题是Content-Type应该是x <- c(" 1st pick ", " 2nd pick " ," 4th pick " ," 5th pick ", " 6th pick " ," 7th pick ", " 8th pick ", " 9th pick " ," 10th pick " ," 11th pick " ," 12th pick " ," 13th pick " ) 而不是application/x-www-form-urlencoded,而且发送带有这种Content-Type的参数的方式也会有所改变。

我做了一个小测试,这段代码对我有用:

application/json

以字符串的形式获取params我做了这个扩展:

static func generateAccessToken() {

    let params = ["client_id": "your_id",
                  "client_secret": "your_client_secret",
                  "grant_type": "authorization_code",
                  "redirect_uri": "http://tolkianaa.blogspot.com/",
                  "code": "the_code"]


    guard let url = NSURL(string: "https://api.instagram.com/oauth/access_token") else {
        return
    }
    let request = NSMutableURLRequest(URL: url)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.HTTPMethod = "POST"

    let stringParams = params.paramsString()
    let dataParams = stringParams.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
    let paramsLength = String(format: "%d", dataParams!.length)
    request.setValue(paramsLength, forHTTPHeaderField: "Content-Length")
    request.HTTPBody = dataParams

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in
        var json: AnyObject = [:]

        guard let data = data else {
            return
        }

        do {
            json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
        } catch {
            // Do nothing
        }

        print(json)
    }

    task.resume()
}

}

希望它有所帮助!

相关问题