首页 > 系统 > iOS > 正文

iOS应用中发送HTTP的get请求以及HTTP异步请求的方法

2020-07-26 03:27:04
字体:
来源:转载
供稿:网友

Http get 请求

复制代码 代码如下:

// 组合一个搜索字符串
    NSString *urlStr = [NSString stringWithFormat:@"http://www.baidu.com/s?wd=%@", @"php"];
    // 字符串转化为URL
    NSURL *url = [NSURL URLWithString:urlStr];
    
//    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
//    [request setURL:url];
//    [request setHTTPMethod:@"POST"];
//    [request setTimeoutInterval:60];
//    [request setHTTPBody:_data];
//    [request setValue:@"ttt" forHTTPHeaderField:@"cookies"];
   
    // url转化为一个请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 状态请求
    NSURLResponse *response;
    // 链接一个请求
    NSData *resultData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    // 返回数据转为字符串
    NSData *dataString = [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
    NSLog(@"%@", dataString);
// 解析json吧

Http异步请求

复制代码 代码如下:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _data = [[NSMutableData alloc] init];
    
    // 组合一个搜索字符串
    NSString *urlStr = [NSString stringWithFormat:@"http://www.baidu.com/s?wd=%@", @"php"];
    NSURL *url = [NSURL URLWithString:urlStr];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    //发起请求,定义代理
    [NSURLConnection connectionWithRequest:request delegate:self];
    
}
 
// 分批返回数据
- (void)connection:(NSURLConnection *) connection didReceiveData:(NSData *)data {
    [_data appendData:data];
    NSLog(@"%@", _data);
}
 
// 数据完全返回完毕
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSString *dataString =  [[NSString alloc] initWithData:_data encoding:NSUTF8StringEncoding];
    NSLog(@"%@", dataString);
}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表