NSURLSessionDataTask发送Get/Post请求

本文介绍了一个使用NSURLSession在iOS应用中发送POST请求的例子。通过创建一个ViewController类,并在其中实现post方法来发起POST请求到指定URL,同时设置请求体内容为用户名和密码。另外还提供了一个GET请求的方法作为对比。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<span style="font-size:14px;">//
//  ViewController.m
//  NSURLSession
//
//  Created by hq on 16/4/17.
//  Copyright © 2016年 hanqing. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
}

-(void) post{
    
    NSURLSession *session=[NSURLSession sharedSession];
    
    NSString *urlString=@"http://xxxx/login";
    
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    
    request.HTTPMethod=@"POST";
    
    request.HTTPBody=[@"username=aa&pwd=aa" dataUsingEncoding:NSUTF8StringEncoding];
    
    NSURLSessionDataTask *task=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
        
    }];
    
    [task resume];
    
}

-(void) dataTaskWithURL{
    
    //获取session对象
    NSURLSession *session=[NSURLSession sharedSession];
    
    NSString *urlString=@"http://120.25.226.186:32812/login?username=aa&pwd=aa";
    
    NSURLSessionDataTask *task=[session dataTaskWithURL:[NSURL URLWithString: urlString] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
        
    }];
    
    [task resume];
}

@end
</span>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值