连接到iOS中需要用户名和密码的JSON API

时间:2014-05-14 09:22:02

标签: ios objective-c json cocoa

我有一个URL,当输入浏览器(EG 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 error 3840。)”

我哪里错了?提前谢谢。

3 个答案:

答案 0 :(得分:0)

 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服务登录的示例代码

答案 1 :(得分:0)

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

-(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");
}


}

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

用a:

连接
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);

}


}

答案 2 :(得分:0)

我建议每当处理网络时都使用AFNetworking

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