美文网首页
利用聚合api学习get,post网络请求

利用聚合api学习get,post网络请求

作者: ZsIsMe | 来源:发表于2015-06-15 11:53 被阅读366次

//发送GET 同步请求

- (void)sendSynNetWorking{

//创建urlString

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

//创建URL

NSURL *url = [NSURL URLWithString:urlString];

//创建请求

NSURLRequest *request = [NSURLRequest requestWithURL:url];

NSError *error = nil;

//发送请求

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

//把NSData转成JSON

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

NSLog(@"%@",object);

}

//发送POST 异步请求

- (void)sendAsynWithPostNetWorking{

//先配置请求参数

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];

//创建urlString

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

//创建URL

NSURL *url = [NSURL URLWithString:urlString];

//创建请求

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

[request setHTTPMethod:@"POST"];

[request setHTTPBody:body];

//发送请求

[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(@"接受数据");

[self.data appendData:data];

}

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

NSLog(@"数据接受完成");

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

//把NSData转成JSON

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

NSLog(@"%@",object);

}

相关文章

网友评论

      本文标题:利用聚合api学习get,post网络请求

      本文链接:https://www.haomeiwen.com/subject/xgcdqttx.html