我有一个没有使用任何第三方位的工作 http GET,我是 iOS 新手,所以最初设置起来很困难。我的代码如下所示:
-(NSString *) SendGetRequestToRest:(NSString *)urlEndString
{
NSString *userName = @"userN";
NSString *password = @"PassW";
NSString *urlBaseString = @"http://someurl.co.uk/";
NSString *urlString = [NSString stringWithFormat:@"%@%@", urlBaseString, urlEndString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"GET"];
NSString *str1 = [NSString stringWithFormat:@"%@:%@", userName, password];
NSString *encodedString = [self stringByBase64EncodingWithString:str1];
[request addValue:[NSString stringWithFormat:@"Basic %@",encodedString] forHTTPHeaderField:@"Authorization"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *str = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"str: %@", str);
return str;
}
我需要做的是跟踪 http GET 的状态代码不是很好的 200 时,我看到了如何在 iOS 中检查 Web 服务器的状态?这看起来很有希望,即添加以下内容:
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response
{
if ([response statusCode] == 404)
{
/// do some stuff
}
}
但我看不到如何将其连接到
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
因为它不接受代表?