[英]Webservice connecting do database with IOS, PHP, REST API, JSON
[英]Connecting to a JSON API in iOS that requires a user name and password
我有一个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错误:操作无法完成。(可可错误3840。)”
我要去哪里错了? 提前致谢。
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服务登录的示例代码
终于解决了。 采用:
-(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);
}
}
我建议在处理网络时都使用AFNetworking 。
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:username
password:password];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.