[英]Connecting to a JSON API in iOS that requires a user name and password
I have a URL that when typed into a browser (EG Safari) requests a username and password, the response API comes back in the form of JSON. 我有一个URL,当键入浏览器(EG Safari)时会请求用户名和密码,响应API以JSON形式返回。
Now I'm trying to connect to this API in my iOS app so I can work with the JSON data and I'm not sure if I'm going about it the correct way. 现在,我试图在我的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");
}
The NSLog is coming back with a "connection success" response. NSLog将返回“连接成功”响应。 However, I can't seem to load the JSON response into an NSDictionary or NSArray. 但是,我似乎无法将JSON响应加载到NSDictionary或NSArray中。 I've used NSJSONSerialization here. 我在这里使用了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);
}
}
And here is my JSON error from the NSLog: "JSON ERROR: The operation couldn't be completed. (Cocoa error 3840.)" 这是我从NSLog发出的JSON错误:“ JSON错误:操作无法完成。(可可错误3840。)”
Where am I going wrong? 我要去哪里错了? Thanks in advance. 提前致谢。
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");
}
Example code for login using json web services 使用JSON Web服务登录的示例代码
Finally resolved this. 终于解决了。 Use: 采用:
-(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");
}
}
You actually don't need to set request values (eg: [request setValue:postLength forHTTPHeaderField:@"Content-Length"];) etc etc 您实际上不需要设置请求值(例如:[request setValue:postLength forHTTPHeaderField:@“ Content-Length”];)等
Connect with a: 连接一个:
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
and handle the JSON response data with: 并使用以下命令处理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);
}
}
I suggest use AFNetworking whenever deal with networking. 我建议在处理网络时都使用AFNetworking 。
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:username
password:password];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.