NSURLConnection的使用 - POST请求

POST请求和GET请求相像
0.首先得有一个NSURL,告诉请求路径。此时POST请求的请求参数不是放请求路径(放在请求体里)

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //1.请求路径
    NSURL * url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
    //2.创建请求对象
    NSMutableURLRequest *requset = [NSMutableURLRequest requestWithURL:url];
    //告知是GET请求还是POST请求
    //更改请求方法,不写的话就是GET
    requset.HTTPMethod = @"POST";
    //设置请求体
    requset.HTTPBody = [@"username=520it&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding];
    //设置超时(5秒后超时)只有用NSMutableURLRequest才行
    requset.timeoutInterval = 5;
    //设置请求头
//    [requset setValue:@"iOS 9.0" forHTTPHeaderField:@"User-Agent"];
    //3.发送请求
    [NSURLConnection sendAsynchronousRequest:requset queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError) {//比如请求超时
            NSLog(@"----请求失败");
        }else{
            NSLog(@"----%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        }        
    }];
}

NSMutableURLRequest
》设置请求超时等待时间(超过这个时间,请求失败)
timeoutInterval/setTimeoutInterval
》设置请求体
HTTPBody/setHTTPBody
》设置请求头
setValue:value forHTTPHeaderField:

创建GET和POST请求

创建GET请求

请求路径 -> 转成 url -> NSURLRequest
默认就是GET请求

NSURL * url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=123"];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:...];

创建POST请求

url -> requset ->改成POST ->请求体

NSURL * url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
 NSMutableURLRequest *requset = [NSMutableURLRequest requestWithURL:url];
 requset.HTTPMethod = @"POST";
requset.HTTPBody = [@"username=520it&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding];
[NSURLConnection sendAsynchronousRequest:...];

两者区别比较的大的地方就在请求参数

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容