IOS網路請求Get,Post請求差異及用法

2021-07-31 22:39:36 字數 2914 閱讀 9965

#pragma

mark

-get

請求// 1.url

nsurl

*url =[

nsurl

urlwithstring

:@""

];// 2.封裝請求

nsurlrequest

*request =[

nsurlrequest

requestwithurl

:url cachepolicy

:nsurlrequestreturncachedataelseload

timeoutinterval:10

];// 3.傳送請求

nsurlresponse

*response

=nil

;nserror

*error

=nil

;// 該方法在ios9.0之後被廢棄

// 下面的方法有3個引數,引數分別為nsurlrequest,nsurlresponse**,nserror**,後面兩個引數之所以傳位址進來是為了在執行該方法的時候在方法的內部修改引數的值。這種方法相當於讓乙個方法有了多個返回值

nsdata

*data =[

nsurlconnection

sendsynchronousrequest

:request returningresponse

:&response error

:&error

];// 錯誤資訊if(

error

)nserror

*newerror

=nil

;nsdictionary

*dictionary =[

nsjsonserialization

jsonobjectwithdata

:data options

:nsjsonreadingmutablecontainers

error

:&newerror

];// 獲取對應的資料資訊

nsarray

*array

=dictionary

[@"news"

];nsdictionary

*dic

=array[0

];nslog

(@"%@"

,dic

[@"title"

]);

ios9之後http的適配方法(千萬記得,不然你會一直納悶鏈結是對的,為什麼就是會崩或者沒有資料):

post請求和get請求的區別在於,post會將請求引數以請求體的形式儲存起來,在向伺服器傳送請求時,我們不會看到裡面的具體引數,例如當我們填寫私密表單,或者登入什麼賬號的時候,自然是不希望別人能看到我們的賬號密碼,所以這時候採用post請求更為安全。

#pragma

mark

-post

請求// 1.獲取請求**

nsurl

*url =[

nsurl

urlwithstring

:@""

];// 2.封裝請求

nsmutableurlrequest

*request =[

nsmutableurlrequest

requestwithurl

:url cachepolicy

:nsurlrequestuseprotocolcachepolicy

timeoutinterval:10

];// post

// 設定請求方式

];// 設定請求體(會把請求的資料轉成data,達到使用者資訊保密的目的)

];// 3.傳送請求

nsurlresponse

*response

=nil

;nserror

*error

=nil

;nsdata

*content =[

nsurlconnection

sendsynchronousrequest

:request returningresponse

:&response error

:&error

];nserror

*newerror

=nil

;// 獲取資料

nsdictionary

*dict =[

nsjsonserialization

jsonobjectwithdata

:content options

:nsjsonreadingmutablecontainers

error

:&newerror

];nsarray

*array

=dict

[@"news"

];nsdictionary

*dic

=array[0

];nslog

(@"%@"

,dic

[@"title"

]);

以上兩種請求所獲取的資料一致,只是採用了不同的方式而已。

關於這節**裡面的細節,比如json資料的解析,這一塊會在後面講解裡介紹,現在只需要知道它是一種資料結構,可以獲取我們需要的資料。

iOS 資料請求 get post

以下是一些簡單關於網路的常識 超文字傳輸協議 hypertext transfer protocol http 規定客服端和伺服器之間的傳輸格式 為什麼選擇使用http 1.簡單快速http協議簡單伺服器程式規模小所以通訊快速 2.靈活可以傳輸任意資料型別 3.http 是非持續鏈結限制每次只處理乙...

網路請求 Get Post 方法(整理)

有兩種方法把資料提交給伺服器 get和post get get 的語義是獲取指定 url上的資源 將資料按照variable value的形式,新增到action所指向的url後面,並且兩者使用 連線,各個變數之間使用 連線 不安全,因為在傳輸過程中,資料被放在請求的url中 傳輸的資料量小,這主要...

iOS 網路請求

pragma mark 網路請求 方式 非同步 ibaction delegatebuttondidclicked uibutton sender 方法 客戶端收到伺服器的響應 pragma mark 客戶端收到伺服器的響應 void connection nsurlconnection conne...