POST 请求 GET请求

GET:

 参数:username 和 password

 1.GET的请求都拼接在url中

 2.?后面是跟的参数 ?前面跟的都是接口

 3.参数的形式key = value&key2=value2

 对于GET请求 所有得参数都拼接在url中,这样暴露在外面 会造成数据的不安全

 url的长度是有限制的 如果参数过于长的话,是不能拼接在url中的

 GET请求会默认在本地缓存

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    NSLog(@"touchesBegan");
    // 创建请求
    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/login/login.php?username=zhangsan&password=zhang"];
    // 这种请求方式默认就是GET请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    // 发送请求
    [[[NSURLSession sharedSession]dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
    }]resume];

}

POST :

 特点:

 1.POST请求的参数都放在都放在请求体中 理论上没有长度限制

 2.外界查看不到POST请求参数的内容,POST请求比GET请求安全,涉及到私密信息,一定要用POST请求

 3.POST请求默认不会缓存在本地

 POST  必须设置可变的请求 不可变的请求是不可以的

 文件上传只能用POST请求

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    NSLog(@"touchBegan");
    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/login/login.php"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [self getRequestBody];
    [[[NSURLSession sharedSession]dataTaskWithRequest: request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
    }]resume];
}

// 获取POST的请求体
- (NSData *)getRequestBody{
    
    NSString *bodyStr = @"username=zhangsan&password=zhang";
    // 将请求参数转换成二进制数据
    NSData *data = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    return data;
}
原文地址:https://www.cnblogs.com/zhubaofeng/p/5274307.html