iOS9 - NSURLSession无法解析响应,但AlamoFire可以正常工作

时间:2016-08-26 04:34:37

标签: swift ios9 alamofire nsurlsession

我正试图从AlamoFire转移到NSURLSessions并尝试向返回GET(字典数组)的端点发出JSON请求。

以下是来自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

以下是我在header中配置的NSURLSession

 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 个答案:

答案 0 :(得分:0)

Content-Length = 2一直显示在标题中的原因是因为我正在为字典发送一个空字符串。当我发送一个nil时,它的作品很有魅力。