iOS网络请求基础知识

作者: Lonely__M | 来源:发表于2015-07-01 11:54 被阅读819次
    • get请求
    NSString *urlStr = [NSString stringWithFormat:@"http://13057506160.xicp.net/api/chguserinfo?name=%@&age=%@&address=%@&sex=%@&info=%@",@"admin",@"20",@"nanjing",@"男",@"succ"];
        //中文编码格式
        urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
        NSURL *url = [NSURL URLWithString:urlStr];
    
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
    
       [conn start];
    
    • post 请求
    NSString *urlStr = [NSString stringWithFormat:@"http://13057506160.xicp.net/api/chguserinfo"];
            //中文编码格式
        NSURL *url = [NSURL URLWithString:urlStr];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        NSString *dataStr = [NSString stringWithFormat:@"name=%@&age=%@&address=%@&sex=%@&info=%@",@"mahong",@"20",@"nanjing",@"nan",@"succ"];
        NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
        
        [request setHTTPBody:data];
        [request setHTTPMethod:@"POST"];
        [request setTimeoutInterval:5];
        
        NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
        [conn start];
    
    • 实现NSURLConnectionDataDelegate代理方法
    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
        NSLog(@"开始接收数据");
    }
    
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
        [resultData appendData:data];
    }
    
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
        NSLog(@"请求错误");
    }
    
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
        NSString *result = [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
        NSLog(@"请求结果:%@",result);
    }
    

    tip

    • 对数组进行排序方法
     arr = [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
           
            NSComparisonResult result = [obj1 compare:obj2];
            return  result == NSOrderedDescending;
        }];
    

    相关文章

      网友评论

      本文标题:iOS网络请求基础知识

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