【问题标题】:Connecting to a JSON API in iOS that requires a user name and password在 iOS 中连接到需要用户名和密码的 JSON API
【发布时间】: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


【解决方案1】:
 NSString *jsonstring = [NSString stringWithFormat:@"{\"userName\":\"%@\",\"password\":\"%@\",\"loginFrom\":\"2\",\"loginIp\":\"%@\"}",[username_text removequotes],[password_text removequotes],ipaddress];//The removeQuotes method is used to escape sequence the " to \" so that the json structure won't break. If the user give " in the username or password field and if we dint handle that the json structure will break and may give an expection.
NSLog(@"the json string we are sending is %@",jsonstring);
NSData *strdata = [json1  dataUsingEncoding:NSUTF8StringEncoding];
NSString *fixedURL =[NSString stringWithFormat:@"%@",loginURL];//the url is saved in loginURL variable.
NSURL *url = [NSURL URLWithString:fixedURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[request setHTTPMethod:@"POST"];
[request setHTTPBody: strdata];
conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) {
    NSLog(@"Connected to service waiting for response");
}

使用 json web 服务登录的示例代码

【讨论】:

  • 你能说得更具体点吗?如“removequotes”、“removeEnter”和loginEndpoint方法是什么?
【解决方案2】:

终于解决了这个问题。使用:

-(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {

if ([challenge previousFailureCount] == 0) {
    NSLog(@"received authentication challenge");
    NSURLCredential *newCredential = [NSURLCredential credentialWithUser:@"username"
                                                                password:@"password"
                                                             persistence:NSURLCredentialPersistenceForSession];
    NSLog(@"credential created");
    [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
    NSLog(@"responded to authentication challenge");
}
else {
    NSLog(@"previous authentication failure");
}


}

您实际上不需要设置请求值(例如:[request setValue:postLength forHTTPHeaderField:@"Content-Length"];)等等等等

连接一个:

NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];

并使用以下方式处理 JSON 响应数据:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

urlData = [[NSMutableData alloc] init];
NSLog(@"DID RECEIVE RESPONSE");
}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data {

NSLog(@"THE RAW DATA IS %@", data);
[urlData appendData:data];

NSString *strRes = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

NSLog(@"LOGGING THE DATA STRING %@", strRes);

}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

NSLog(@"FINISHED LOADING DATA %@", connection);

NSError *jsonParsingError = nil;
//id object = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&jsonParsingError];
NSArray *parsedObject = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&jsonParsingError];

NSLog(@"RESPONSE: %@",[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding]);


if (jsonParsingError) {
    NSLog(@"JSON ERROR: %@", [jsonParsingError localizedDescription]);
} else {
    NSLog(@"PARSED OBJECT %@", parsedObject);

}


}

【讨论】:

    【解决方案3】:

    我建议在处理网络时使用AFNetworking

    [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:username
                                                              password:password];
    

    【讨论】:

      猜你喜欢
      • 2020-12-09
      • 1970-01-01
      • 2011-03-24
      • 2016-06-06
      • 1970-01-01
      • 2014-04-02
      • 1970-01-01
      相关资源
      最近更新 更多