1.Get請求
//get把傳輸的數據 放在鏈接地址里面- (void)getRequest{ NSString *interfaceString = @"http://apis.baidu.com/showapi_open_bus/mobile/find"; NSString *requestContentString = @"num=15761672938"; NSString *urlString = [NSString stringWithFormat:@"%@?%@",interfaceString,requestContentString]; NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];// 可變請求 可以添加請求方式 以及請求的 請求頭 或者更多// timeoutInterval請求所需時間 超過所需時間 超過時間不再發送這個請求// cachePolicy緩存內容的方式 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUsePRotocolCachePolicy timeoutInterval:10]; NSString *apiKey = @"e7f5ac9e7c42a6c8cb125ee1d7e8779e";// 把apiKey 發送給服務器 指定的請求 位置// forHTTPHeaderField需要的Key 是服務器指定的key [request addValue:apiKey forHTTPHeaderField:@"apiKey"]; // 指定http的請求方式 request.HTTPMethod = @"GET";//一般都是大寫 [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSLog(@"%@",response); // 解析json文件 // 把data轉換成json文件 NSDictionary *info = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; NSLog(@"%@",info); NSLog(@"info===%@ ,%@%@",info[@"showapi_res_body"][@"name"],info[@"showapi_res_body"][@"prov"],info[@"showapi_res_body"][@"city"]); }];}
2.Post請求
//post- (void)postRequest{ NSURL *url = [NSURL URLWithString:@"http://www.weihuok.com/customer2/GetService"];// 請求參數// PlatformType設備類型 3表示ios設備 NSDictionary *dic = @{@"PlatformType":@"3"}; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];// 設置請求方式 request.HTTPMethod = @"POST";// 設置 請求的參數// HTTPBody要的是data// dataUsingEncoding把字符串轉成data request.HTTPBody = [[NSString stringWithFormat:@"%@",dic]dataUsingEncoding:NSUTF8StringEncoding]; [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSDictionary *info = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; NSLog(@"==%@",info); }]; }
3.HTTP Get請求
GET URL 字符串地址 parameters boby體的內容
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"" parameters:nil success:^(AFHTTPRequestOperation *operation, id responSEObject) {
// responseObject請求下來的數據內容
} failure:^(AFHTTPRequestOperation *operation, NSError * error) {
}];
4.HTTP Post請求
//post parameters需要post的內容
[manager POST:@"" parameters:@{} success:^(AFHTTPRequestOperation * operation, id responseObject) {
} failure:^(AFHTTPRequestOperation * operation, NSError * error) {
}];
新聞熱點
疑難解答