NSURLConnection获取数据

- (void)loadDataFromUrl
{
    NSURL* url = [NSURL URLWithString:@"http://m.weather.com.cn/data/101190408.html"];
    NSMutableURLRequest * urlRequest=[NSMutableURLRequest requestWithURL:url];
    NSURLConnection* urlConn = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
    [urlConn start];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse*)response
{
    NSHTTPURLResponse* rsp = (NSHTTPURLResponse*)response;
    int code = [rsp statusCode];
    if (code != 200)
    {
        [connection cancel];
        [connection release];
        connection = nil;
    }
    else
    {
        if (mData != nil)
        {
            [mData release];
            mData = nil;
        }
        mData = [[NSMutableData alloc] init];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [mData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
   // [self hideAlert];
    NSString* backString = [[NSMutableString alloc] initWithData:mData encoding:NSUTF8StringEncoding];
    NSMutableDictionary *backData  =[backString JSONValue];
    NSLog(@"%@",backData);
    connection = nil;
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [connection release];
    connection = nil;
}

-(void)showAlertView:(NSString*)titleStr
{
    UIAlertView *myalert = [[UIAlertView alloc]
                            initWithTitle:@"提示"
                            message:titleStr
                            delegate:self
                            cancelButtonTitle:@"取消"
                            otherButtonTitles:nil];
    [myalert show];
    [myalert release];
}

 

posted on 2013-11-01 16:19  jack_yan  阅读(292)  评论(0)    收藏  举报