![](/img/trans.png)
[英]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.