<span style="font-family:SimHei;font-size:24px;"></span>
</pre><pre name="code" class="objc"><span style="font-family:SimHei;font-size:24px;"></span>
</pre><pre name="code" class="objc"><span style="font-family:SimHei;font-size:24px;">我们经常要在代码中通过网络请求来获得数据,其中的一种方法就是get方法,下面为异步请求方法:</span>
<span style="font-family:SimHei;font-size:24px;">先要创建一个名字为Connection的继承于nsobject的类;</span>
<span style="font-family:SimHei;font-size:24px;">在.h文件中需要遵循一下<<span style="color: rgb(52, 149, 175);">NSURLConnectionDataDelegate</span>><span style="color: rgb(52, 149, 175);">协议</span></span>
<span style="font-family:SimHei;font-size:24px;">然后写一个类方法组作为接口:</span>
+ (void)connectionWithUrl:(NSString *)strUrl parmaters:(NSDictionary *)parmaters delegate:(id<ConnectionDelegate>)delegate flag:(NSInteger)flag;
// 网址分为两部分,一部分是固定的,一部分是参数
- (void)startRequest:(NSString *)urlStr parmaters:(NSDictionary *)parmaters
{
NSString *str = @"";
网址的拼接:
for (NSString *key in [parmaters allKeys]) {
if ([str length] == 0) {
str = [NSString stringWithFormat:@"?%@=%@", key, [parmaters objectForKey:key]];
}
else
{
str = [NSString stringWithFormat:@"%@&%@=%@", str, key, [parmaters objectForKey:key]];
}
}
// 网址不能有空格和汉字
str = [NSString stringWithFormat:@"%@%@", urlStr, str];
str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// NSLog(@"%@", str);
NSURL *url = [NSURL URLWithString:str];
封装为request请求:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"GET"];
建立连接:
[NSURLConnection connectionWithRequest:request delegate:self];
}
+ (void)connectionWithUrl:(NSString *)strUrl parmaters:(NSDictionary *)parmaters delegate:(id<ConnectionDelegate>)delegate flag:(NSInteger)flag
{
Connection *con = [[Connection alloc] init];
con.delegate = delegate;
con.flag = flag;
[con startRequest:strUrl parmaters:parmaters];
[con release];
}
协议执行:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
将数据进行拼接:
[self.data appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
用协议将数据返回:
if ([self.delegate respondsToSelector:@selector(selData:flag:)]) {
[self.delegate selData:self.data flag:self.flag];
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
}
<span style="font-family:SimHei;"></span>