IOS開發之網路同步GET請求

2021-07-22 01:14:59 字數 2112 閱讀 9205

在網路請求中,http網路請求使用的最多,不管是獲取文字還是獲取二進位制資料,亦或是將資料提交到伺服器上。http請求使用起來最為簡單,http請求型別分為好幾種,例如:get,post,put,delete。這其中最為常見的兩種形式就是get和post。

get是用來從伺服器上獲得資料的請求方式。

同步請求的步驟如下:

1.建立nsurl

//利用uibutton建立乙個方法

- (ibaction)synchronizedget:(uibutton *)sender

2.通過nsurl建立nsurlrequest請求

nsurlrequest *request = [nsurlrequest requestwithurl:url cachepolicy:nsurlrequestuseprotocolcachepolicy timeoutinterval:60];
3.使用nsurlconnection 類和伺服器連線,這個是同步過程

nsdata *data = [nsurlconnection sendsynchronousrequest:request returningresponse:&httpurlresponse error:&error];4.資料完成之後進行處理

//json資料格式解析,利用系統提供的api進行json資料解析

nsdictionary *dictionary = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingallowfragments error:nil];

nsdictionary *dic = [dictionary[@"statuses"] objectatindex:0];

nsstring *text = dic[@"text"];

self

.textview

.text = text;

//2.建立乙個weibomodel類(mvc模式,這裡相當於建立乙個model)

//weibomodel類中有以下屬性

@property (nonatomic,strong)nsarray *statuses;

@property (nonatomic,strong)nsnumber *hasvisible;

@property (nonatomic,strong)nsnumber *previous_cursor;

@property (nonatomic,strong)nsnumber *next_cursor;

@property (nonatomic,strong)nsnumber *total_number;

@property (nonatomic,strong)nsnumber *interval;

//建立乙個方法,傳入乙個字典,通過model物件設定其屬性

- (id)initwithdictionary:(nsdictionary *)dictionary;

//方法的實現

- (id)initwithdictionary:(nsdictionary *)dictionary

return

self;

}//json資料格式解析,利用系統提供的api進行json資料解析

nsdictionary *dictionary = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingallowfragments error:nil];

//建立乙個model

weibomodel *model = [[weibomodel alloc] initwithdictionary:dictionary];

nsstring *text = [model.statuses[0] objectforkey:@"text"];

self

.textview

.text = text;

iOS開發網路篇 GET請求和POST請求

一 get請求和post請求簡單說明 建立get請求 1 1.設定請求路徑 2 nsstring urlstr nsstring stringwithformat self.username.text,self.pwd.text 3 nsurl url nsurl urlwithstring url...

iOS開發網路篇 GET請求和POST請求

一 get請求和post請求簡單說明 建立get請求 1 1.設定請求路徑 2 nsstring urlstr nsstring stringwithformat self.username.text,self.pwd.text 3 nsurl url nsurl urlwithstring url...

ios開發網路篇 Get請求和Post請求

一.get請求和post請求簡單說明 建立get請求 1.設定請求路徑 nsstring urlstr nsstring stringwithformat self username text,self pwd text nsurl url nsurl urlwithstring urlstr 2....