Swift-Alamofire URLEncoding &am

2018-03-21  本文已影响798人  DSA碼侬

请求代码如下:

 // 参数
   let param = ["access_token": (UserAccountViewModel.shareInstance.account?.access_token)!]
    
    
    Alamofire.request("https://api.weibo.com/2/statuses/home_timeline.json", method: .get, parameters: param, encoding: JSONEncoding.default, headers: nil).responseJSON { (dataResponse) in
        
        print("request---\(dataResponse.request!)")
        print("response---\(dataResponse.response)")
        print("data---\(dataResponse.data)")
        print("resultValue---\(dataResponse.result.value)")
       
    }

打印结果:

 request---https://api.weibo.com/2/statuses/home_timeline.json
 response---Optional( { URL: https://api.weibo.com/2/statuses/home_timeline.json } { status code: 403, headers {
"Content-Encoding" = gzip;
"Content-Type" = "application/json;charset=UTF-8";
Date = "Wed, 15 Nov 2017 07:38:42 GMT";
Server = "nginx/1.6.1";
Vary = "Accept-Encoding";
"api-server-ip" = "10.75.5.93";
} })
data---Optional(91 bytes)
resultValue---Optional({
error = "auth by Null spi!";
"error_code" = 21301;
request = "/2/statuses/home_timeline.json";

})

分析:
获得数据失败,打印结果得知request=https://api.weibo.com/2/statuses/home_timeline.json没有拼接参数,如果把encoding值改为URLEncoding.default是会有正确结果打印的

如果是get请求 需要拼接字符串 那么就使用

 URLEncoding.default 

或者

 URLEncoding(destination: .methodDependent)  

说明:

1、JSONEncoding.default 是放在HttpBody内的, 比如post请求
2、URLEncoding.defaultGET中是拼接地址的, 比如get请求
3、URLEncoding(destination: .methodDependent) 是自定义的URLEncodingmethodDependent的值如果是在GETHEADDELETE中就是拼接地址的。其他方法方式是放在httpBody内的。
4、URLEncoding(destination: .httpbody)是放在httpbody内的

上一篇 下一篇

猜你喜欢

热点阅读