ios 异步 GET请求、POST请求

qianchunqiang 2014-04-21

3、异步GET请求

    //第一步,创建url

    NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do?type=focus-c"];

    //第二步,创建请求

    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

    //第三步,连接服务器

    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];

[connection start];

4、异步POST请求

    //第一步,创建url

    NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do"];

    //第二步,创建请求

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

    [request setHTTPMethod:@"POST"];

    NSString *str = @"type=focus-c";

    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

    [request setHTTPBody:data];

    //第三步,连接服务器

    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];

5、异步请求的代理方法

//接收到服务器回应的时候调用此方法

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

{

    NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;

    NSLog(@"%@",[res allHeaderFields]);

    self.receiveData = [NSMutableData data];

  

                              

}

//接收到服务器传输数据的时候调用,此方法根据数据大小执行若干次

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

{

    [self.receiveData appendData:data];

}

//数据传完之后调用此方法

-(void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    NSString *receiveStr = [[NSString alloc]initWithData:self.receiveData encoding:NSUTF8StringEncoding];

    NSLog(@"%@",receiveStr);

}

//网络请求过程中,出现任何错误(断网,连接超时等)会进入此方法

-(void)connection:(NSURLConnection *)connection

 didFailWithError:(NSError *)error

{

    NSLog(@"%@",[error localizedDescription]);

相关推荐