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);
    }   

  • 相关阅读:
    Mac Terminal菜鸟篇之使用unrar解压rar文件
    Android开发之帐户管理
    Android API之android.view.View.MeasureSpec
    Android API之onLayout, onMeasure
    Android API之android.os.AsyncTask
    Android开发之Shortcuts, LiveFolder, Widget
    Android开发之短信
    Android系统示例分析之AndroidBeamDemo
    Android开发之定位系统
    Android系统示例之ActionBarCompat
  • 原文地址:https://www.cnblogs.com/linxiu-0925/p/5070284.html
Copyright © 2011-2022 走看看