到目前为止,这是我NSURLSessionUploadTask
:
NSURLSessionUploadTask
HTTP/1.1 200 OK Server: BaseHTTP/0.3 Python/2.7.10 Date: Fri, 30 Oct 2015 16:15:21 GMT Content-Type: text/html Content-Length: 96 <html><head><title>POST RESPONSE</title></head><body><p>The file was uploaded.</p></body></html>
NSLogs
NSURLSessionTaskDelegate -> URLSession:task:didCompleteWithError:
回复
<NSHTTPURLResponse: 0x15d95110> { URL: http://10.157.239.129:42000/ } { status code: 200, headers { "Content-Length" = 96; "Content-Type" = "text/html"; Date = "Fri, 30 Oct 2015 16:15:21 GMT"; Server = "BaseHTTP/0.3 Python/2.7.10"; } }
NSLog
NSURLSessionTaskDelegate: -> URLSession:dataTask:didReceiveData:
响应内容
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { // Called when data task has received some data (not applicable for straight upload?) if (data != NULL) { NSLog(@"%s: %@", __PRETTY_FUNCTION__,[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); } else { NSLog(@"%s: but no actual data received.", __PRETTY_FUNCTION__); } // If we are not in the "active" or foreground then log some background information to the console if (UIApplication.sharedApplication.applicationState != UIApplicationStateActive) { [BackgroundTimeRemainingUtility NSLog]; } }
2015-10-30 12:15:22.648 NSURLSessionUploadTaskExample[215:7286] -[ViewController URLSession:dataTask:didReceiveData:]: (null)
有谁可以告诉我为什么iOS似乎丢失了HTTP响应中的内容?
答案 0 :(得分:0)
因为我能够跟踪从服务器到iOS应用程序的HTTP 200响应,所以我怀疑iOS应用程序有问题。我在这一行设置了一个断点:
NSLog(@"%s: %@", __PRETTY_FUNCTION__,[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
并使用调试器检查data
对象:
响应内容中的每个96字节都到达NSURLSessionTaskDelegate: -> URLSession:dataTask:didReceiveData:
因此NSString
中的NSLog
解码出错了。现在事情变得有意义了。我发送的是96字节的ASCII响应,而不是96字节的UTF8响应!
我将NSString
解码器替换为以下内容:
NSLog(@"%s: %@", __PRETTY_FUNCTION__,[[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding: NSASCIIStringEncoding]);
使用以下输出解决了问题:
2015-11-02 10:04:47.086 NSURLSessionUploadTaskExample[561:363449] -[ViewController URLSession:dataTask:didReceiveData:]:<html><head><title>POST RESPONSE</title></head><body><p>The file was uploaded.</p></body></html>
我还在github here上放了一个非常基本的NSURLSessionUploadTask示例应用程序和webserver。