zoukankan      html  css  js  c++  java
  • iOS-NSURLConnection异步发送 HTTP请求

    - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar

    {
     NSString *new = [searchBar.text stringByReplacingOccurrencesOfString:@" " withString:@"+"];
     NSString *urlString = [NSString stringWithFormat:@"http://192.168.1.104/test.php?cid=%@",new];
     NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding (kCFStringEncodingGB_18030_2000);
      NSString *strUrld8 = [urlString stringByAddingPercentEscapesUsingEncoding:enc];
     //调用http get请求方法 
     [self sendRequestByGet:strUrld8];
    }
    //HTTP get请求方法
    - (void)sendRequestByGet:(NSString*)urlString
    {  
     NSURL *url=[NSURL URLWithString:urlString];
     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url
                    cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                   timeoutInterval:60];
     //设置请求方式为get
     [request setHTTPMethod:@"GET"];
     //添加用户会话id
     [request addValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
     //连接发送请求
     receivedData=[[NSMutableData alloc] initWithData:nil];
     NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
     [request release];      
     [conn release];
    }

    - (void)connection:(NSURLConnection *)aConn didReceiveResponse:(NSURLResponse *)response {
        // 注意这里将NSURLResponse对象转换成NSHTTPURLResponse对象才能去
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
        if ([response respondsToSelector:@selector(allHeaderFields)]) {
            NSDictionary *dictionary = [httpResponse allHeaderFields];
            NSLog(@"[email=dictionary=%@]dictionary=%@",[dictionary[/email] description]);
      
        }
    }
    //接收NSData数据
    - (void)connection:(NSURLConnection *)aConn didReceiveData:(NSData *)data {
     [receivedData appendData:data];
    }
    - (void)connection:(NSURLConnection *)aConn didFailWithError:(NSError *)error{
     NSLog(@"[email=error=%@]error=%@",[error[/email] localizedDescription]);
    }
    //接收完毕,显示结果
    - (void)connectionDidFinishLoading:(NSURLConnection *)aConn {
       NSString *results = [[NSString alloc]
                             initWithBytes:[receivedData bytes]
                             length:[receivedData length]
                             encoding:NSUTF8StringEncoding];
     NSLog(@"results=%@",results);
    }   

  • 相关阅读:
    jquery select操作和联动操作
    chrome 31删除输入框的历史记录
    14、python开发之路-并发编程之I/O模型
    13、python开发之路-并发编程之多线程
    12、python全栈之路-并发编程之多进程
    11、python全栈之路-网络编程
    10、python全栈之路-面向对象进阶
    9、python全栈之路-模块与包
    8、python全栈之路-初识面向对象
    6、python全栈之路-常用模块
  • 原文地址:https://www.cnblogs.com/linxiu-0925/p/5070284.html
Copyright © 2011-2022 走看看