同步的 post 請求
#pragma mark - 同步的 post 請求
- (IBAction)POSTSynButtonDidClicked:(UIButton *)sender {
// 1、拼接 baseUrlString
NSString *baseUrlString = @http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx;
// 2、根據字符串創建 URL(統一資源定位符)
NSURL *url = [NSURL URLWithString:baseUrlString];
// 3、創建可變的 request 對象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 1> 設置請求類型為 POST (默認為 GET)
[request setHTTPMethod:@POST];
// 2> 需要設置 POST 參數
NSString *bodyString = @date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213;
// 把字符串轉化為 NSData
NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:bodyData];
// 4、請求數據(同步)
NSData *receiveData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// 5、系統自帶json解析
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:receiveData options:(NSJSONReadingMutableContainers) error:nil];
NSArray *array = dict[@news];
self.newsArray = [NSMutableArray array];
for (NSDictionary *smallDict in array) {
NewsModal *modal = [[NewsModal alloc] init];
[modal setValuesForKeysWithDictionary:smallDict];
[self.newsArray addObject:modal];
}
for (NewsModal *modal in self.newsArray) {
NSLog(@%@, modal.title);
}
}
異步的 post 請求
#pragma mark - 異步的 post 請求
- (IBAction)POSTAsynButtonDidClicked:(UIButton *)sender {
// 1、拼接 baseUrlString
NSString *baseUrlString = @http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx;
// 2、根據字符串創建 url(統一資源定位符)
NSURL *url = [NSURL URLWithString:baseUrlString];
// 3、創建可變 request 對象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 設置 request 對象的相關屬性
// 1>設置默認請求類型為 POST
[request setHTTPMethod:@POST];
// 2>設置POST參數
NSString *bodyString = @date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213;
// 3>把字符串轉化為 NSData
NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:bodyData];
// 4、請求數據(異步)
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// 5、系統自帶json解析
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
NSArray *array = dict[@news];
self.newsArray = [NSMutableArray array];
for (NSDictionary *smallDict in array) {
NewsModal *modal = [[NewsModal alloc] init];
[modal setValuesForKeysWithDictionary:smallDict];
[self.newsArray addObject:modal];
}
for (NewsModal *modal in self.newsArray) {
NSLog(@%@, modal.title);
}
// 對 tableView 進行 reloadData 否則第一次不顯示內容
}];
}