利用聚合api學習get,post網絡請求

//發(fā)送GET 同步請求

- (void)sendSynNetWorking{

//創(chuàng)建urlString

NSString *urlString = @"http://api2.juheapi.com/xiecheng/senicspot/ticket/search?key=815a3cbd22f9127bc8d3d8e1076f7b32&pageindex=1&pagesize=20&keyword=%E6%88%90%E9%83%BD";

//創(chuàng)建URL

NSURL *url = [NSURL URLWithString:urlString];

//創(chuàng)建請求

NSURLRequest *request = [NSURLRequest requestWithURL:url];

NSError *error = nil;

//發(fā)送請求

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];

//把NSData轉成JSON

id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

NSLog(@"%@",object);

}

//發(fā)送POST 異步請求

- (void)sendAsynWithPostNetWorking{

//先配置請求參數(shù)

NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];

[dictionary setObject:@"1" forKey:@"pageindex"];

[dictionary setObject:@"5" forKey:@"pagesize"];

[dictionary setObject:@"上海" forKey:@"keyword"];

[dictionary setObject:@"" forKey:@"key"];//填入api的key

//

NSMutableString *string = [NSMutableString string];

for (NSString *key in dictionary) {

[string appendFormat:@"%@=%@&",key,dictionary[key]];

}

//轉成DATA

NSData *body = [string dataUsingEncoding:NSUTF8StringEncoding];

//創(chuàng)建urlString

NSString *urlString = @"http://api2.juheapi.com/xiecheng/senicspot/ticket/search?";

//創(chuàng)建URL

NSURL *url = [NSURL URLWithString:urlString];

//創(chuàng)建請求

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

[request setHTTPMethod:@"POST"];

[request setHTTPBody:body];

//發(fā)送請求

[NSURLConnection connectionWithRequest:request delegate:self];

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{

NSLog(@"%s",__FUNCTION__);

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

NSLog(@"得到響應");

self.data = [[NSMutableData alloc] init];

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{

NSLog(@"接受數(shù)據(jù)");

[self.data appendData:data];

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{

NSLog(@"數(shù)據(jù)接受完成");

//? ? NSLog(@"%@",self.data);

//把NSData轉成JSON

id object = [NSJSONSerialization JSONObjectWithData:self.data options:NSJSONReadingMutableContainers error:nil];

NSLog(@"%@",object);

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容