iOS9 - NSURLSession 无法解析响应但 AlamoFire 工作
Posted
技术标签:
【中文标题】iOS9 - NSURLSession 无法解析响应但 AlamoFire 工作【英文标题】:iOS9 - NSURLSession fails to parse response but AlamoFire works 【发布时间】:2016-08-26 04:34:37 【问题描述】:我正在尝试从AlamoFire
移动到NSURLSessions
,并尝试向返回JSON
(字典数组)的端点发出GET
请求。
以下是来自Alamofire
代码的标头成功:
GET /Path/?lastrequest=2006-08-25T03:25:21Z HTTP/1.1
Host one.domain.com
Cookie connect.sid=s%3A8gUYZmxHWn9PJ95ZJF9P6FGrdrcPIueG.KcXee%2FT8VI1SeAaVvOwcHdOuCLydPvU%2BLiqlZHu2QfI
x-token $2a$10$Vif5iFua8/EdITuaibyO.ANoGm8EuNORBLjXVaxwSJ.a.1472443117
Accept */*
User-Agent MyApp/com.MyApp.test (1; OS Version 9.3 (Build 13E230))
Accept-Language en-US;q=1.0
Accept-Encoding gzip;q=1.0,compress;q=0.5
Connection keep-alive
AlamoFire
Successful
回复信息:
Size
Request Header 475 bytes
Response Header 173 bytes
Request -
Response 87.66 KB (89762 bytes)
Total 88.29 KB (90410 bytes)
Request Compression -
Response Compression -
Response Code 200 OK
Protocol HTTP/1.1
Method GET
Kept Alive Yes
Content-Type application/json; charset=utf-8
Client Address /127.0.0.1
现在标题使用NSURLSession
失败:
GET /Path/?lastrequest=2006-08-25T03:25:21Z HTTP/1.1
Host one.domain.com
Accept */*
Connection keep-alive
x-token $2a$10$Vif5iFua8/EdITuaibyO.ANoGm8EuNORBLjXVaxwSJ.a.1472443117
Cookie connect.sid=s%3ATRSrme3Q4yLchJu-3KanYLi8lKJgITbh.xO0uUEIFsWQ7McIyA36%2BgJi7aPWb9MYxSEn9nYKzUA8
Accept-Language en-US;q=1.0
Content-Length 2
Accept-Encoding gzip;q=1.0,compress;q=0.5
User-Agent NetworkLayer/1 CFNetwork/758.3.15 Darwin/15.6.0
NSURLSession
失败响应信息:
Size
Request Header 476 bytes
Response Header 173 bytes
Request -
Response 12.73 KB (13032 bytes)
Total 13.36 KB (13681 bytes)
Request Compression -
Response Compression -
我确实在header
中看到了AlamoFire
中没有的额外字段,但我不知道如何关闭它们。
NRURLSession 也在进行 3-4 个并发调用。
NSURLSession
失败回复:
Response: Failed to parse data (org.json.JSONException: A JSONObject text must begin with '' at character 1)
Failure Client closed connection before receiving entire response
Response Code 200 OK
Protocol HTTP/1.1
Method GET
Kept Alive No
Content-Type application/json; charset=utf-8
Client Address /127.0.0.1
这是我在NSURLSession
中配置的header
:
var headers: [String: String]?
return ["x-token" : token!,
"Accept-Encoding": "gzip;q=1.0,compress;q=0.5",
"Accept-Language": "en-US;q=1.0"]
我做错了什么?
【问题讨论】:
是您的端点,还是第三方的?服务器会根据用户代理等原因阻止您吗? 【参考方案1】:Content-Length = 2 一直显示在标题中的原因是因为我为字典发送了一个空字符串。当我改为发送 nil 时,它的效果就像一种魅力。
【讨论】:
以上是关于iOS9 - NSURLSession 无法解析响应但 AlamoFire 工作的主要内容,如果未能解决你的问题,请参考以下文章