如何获取 NSURLResponse
我使用以下命令向 Web 服务器发出 http 请求:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"http://server.com"]];
[request setHTTPMethod: @"POST"];
[request setHTTPBody: myRequestData];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
但是如何从服务器获取响应并解析它呢?多谢 :)
I make http request to the web server with this:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"http://server.com"]];
[request setHTTPMethod: @"POST"];
[request setHTTPBody: myRequestData];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
But how can I get the response from the server and parse it? Thanks a lot :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于您将响应分配给
returnData
实例变量,因此将其转换为字符串,以便初学者只需看看您得到的结果,解析可以使用NSXMLParser
或某些 JSON 库完成,具体取决于关于响应格式。以下是将响应转换为字符串的方法:
Since you're assigning response to
returnData
instance variable, convert it to string for starters just look what you get, the parsing may be done with eitherNSXMLParser
or some JSON library depending on response format.Here's how you'd convert the response to string:
我假设您指的是完整的 NSURLResponse ,以便您可以检查标头等。在这种情况下,您需要传入returningResponse参数,它是一个类型为(NSURLResponse **)的输出参数。请参阅文档。
I assume you mean the full NSURLResponse so that you can inspect headers and the like. In which case you need to pass in the returningResponse parameter, it is an out parameter of type (NSURLResponse **). See the docs.
returnData
是您的响应。如果它是xml那么你可以使用NSXMLParser来解析它,如果它的json使用JSONFramework。returnData
is your response. If its xml then you can use NSXMLParser to parse it, if its json use the JSONFramework.