NSURLConnection的使用 - POST請(qǐng)求

POST請(qǐng)求和GET請(qǐng)求相像
0.首先得有一個(gè)NSURL,告訴請(qǐng)求路徑。此時(shí)POST請(qǐng)求的請(qǐng)求參數(shù)不是放請(qǐng)求路徑(放在請(qǐng)求體里)

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //1.請(qǐng)求路徑
    NSURL * url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
    //2.創(chuàng)建請(qǐng)求對(duì)象
    NSMutableURLRequest *requset = [NSMutableURLRequest requestWithURL:url];
    //告知是GET請(qǐng)求還是POST請(qǐng)求
    //更改請(qǐng)求方法,不寫的話就是GET
    requset.HTTPMethod = @"POST";
    //設(shè)置請(qǐng)求體
    requset.HTTPBody = [@"username=520it&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding];
    //設(shè)置超時(shí)(5秒后超時(shí))只有用NSMutableURLRequest才行
    requset.timeoutInterval = 5;
    //設(shè)置請(qǐng)求頭
//    [requset setValue:@"iOS 9.0" forHTTPHeaderField:@"User-Agent"];
    //3.發(fā)送請(qǐng)求
    [NSURLConnection sendAsynchronousRequest:requset queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError) {//比如請(qǐng)求超時(shí)
            NSLog(@"----請(qǐng)求失敗");
        }else{
            NSLog(@"----%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        }        
    }];
}

NSMutableURLRequest
》設(shè)置請(qǐng)求超時(shí)等待時(shí)間(超過這個(gè)時(shí)間,請(qǐng)求失?。?br> timeoutInterval/setTimeoutInterval
》設(shè)置請(qǐng)求體
HTTPBody/setHTTPBody
》設(shè)置請(qǐng)求頭
setValue:value forHTTPHeaderField:

創(chuàng)建GET和POST請(qǐng)求

創(chuàng)建GET請(qǐng)求

請(qǐng)求路徑 -> 轉(zhuǎn)成 url -> NSURLRequest
默認(rèn)就是GET請(qǐng)求

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

創(chuàng)建POST請(qǐng)求

url -> requset ->改成POST ->請(qǐng)求體

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:...];

兩者區(qū)別比較的大的地方就在請(qǐng)求參數(shù)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容