【发布时间】:2014-07-02 06:20:29
【问题描述】:
我有一个 URL,当我在浏览器(例如 Safari)中输入用户名和密码时,响应 API 会以 JSON 的形式返回。
现在我正尝试在我的 iOS 应用程序中连接到此 API,以便我可以处理 JSON 数据,但我不确定我是否以正确的方式进行操作。
NSString *post = [NSString stringWithFormat:@"&Username=%@&Password=%@",@"username",@"password"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSString *string = [NSString stringWithFormat:@"jsonURL"];
NSURL *url = [NSURL URLWithString:string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
[request setHTTPBody:postData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(connection)
{
NSLog(@"connection success");
}
else
{
NSLog(@"connection could not be made");
}
NSLog 返回“连接成功”响应。但是,我似乎无法将 JSON 响应加载到 NSDictionary 或 NSArray 中。我在这里使用了 NSJSONSerialization。
NSMutableData *urlData;
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
urlData = [[NSMutableData alloc] init];
NSLog(@"DID RECEIVE RESPONSE %@", urlData);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data {
[urlData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"FINISHED LOADING DATA %@", connection);
NSError *jsonParsingError = nil;
NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&jsonParsingError];
if (jsonParsingError) {
NSLog(@"JSON ERROR: %@", [jsonParsingError localizedDescription]);
} else {
NSLog(@"Parsed Object is %@", parsedObject);
}
}
这是来自 NSLog 的 JSON 错误:“JSON 错误:操作无法完成。(Cocoa 错误 3840。)”
我哪里错了?提前致谢。
【问题讨论】:
-
试试这个
NSString *strRes = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];请NSLog这个字符串并添加它,这样我们就可以知道您是否得到了正确的响应。所以我们可以帮助您。 -
在您的 didFinishLoading 方法中,只需检查响应为 NSString,如
NSLog(@"RESPONSE: %@",[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding]); -
我的用户名和密码无效。然而,两者都是正确的,因为它们在浏览器中工作。在浏览器上,我被要求通过输入登录弹出窗口输入用户名和密码。所以我认为问题在于帖子的格式: NSString *post = [NSString stringWithFormat:@"&Username=%@&Password=%@",@"username",@"password"];
标签: ios objective-c json cocoa