陈斌彬的技术博客

Stay foolish,stay hungry

iOS 解析成语大全 API 的 JSON 数据(原创)

API 接口网址

http://apistore.baidu.com/apiworks/servicedetail/501.html

代码示例

- (void)viewDidLoad {
    [super viewDidLoad];

    NSString *data = @"叶";
    //转换成UTF-8
    NSString *dataUTF8 = [data  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    // Do any additional setup after loading the view, typically from a nib.
    NSString *httpUrl = @"http://apis.baidu.com/netpopo/idiom/chengyu";

    //NSString *httpArg = @"keyword=%E5%8F%B6&appkey=1307ee261de8bbcf83830de89caae73f";
    NSString *httpArg  = [[NSString alloc]initWithFormat: @"keyword=%@&appkey=1307ee261de8bbcf83830de89caae73f",dataUTF8];
    [self request: httpUrl withHttpArg: httpArg];
}


-(void)request: (NSString*)httpUrl withHttpArg: (NSString*)HttpArg  {
    NSString *urlStr = [[NSString alloc]initWithFormat: @"%@?%@", httpUrl, HttpArg];
    NSURL *url = [NSURL URLWithString: urlStr];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
    [request setHTTPMethod: @"GET"];
    [request addValue: @"c33bdd6ad06c082a12a171edc323cc9a" forHTTPHeaderField: @"apikey"];
    [NSURLConnection sendAsynchronousRequest: request
                                       queue: [NSOperationQueue mainQueue]
                           completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error){
                               if (error) {
                                   NSLog(@"Httperror: %@%ld", error.localizedDescription, error.code);
                               } else {
                                   NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
                                   NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                   NSLog(@"HttpResponseCode:%ld", responseCode);
                                   NSLog(@"HttpResponseBody %@",responseString);
                               }
                           }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

查看获取结果

img