iOS 使用Socket模擬手機訪問百度

2021-09-19 22:04:20 字數 3195 閱讀 9284

bool result = [self connectip:@"220.181.111.188" port:80];

if (!result)

nslog(@"連線成功");

// 連線伺服器

- (bool)connectip:(nsstring *)ip port:(int)port else }

2. 構造請求頭

// 模擬構造http請求頭

nslog(@"%@", request);

3. 訪問伺服器,並獲取返回內容
// 伺服器返回的響應頭  響應體

nsstring *response = [self sendandrecv:request];

nslog(@"返回的資料: %@", response);

// 傳送和接收資料

- (nsstring *) sendandrecv:(nsstring *)sendmsg

nsstring *recvmsg = [[nsstring alloc] initwithdata:datas encoding:nsutf8stringencoding];

return recvmsg;

}

4. 關閉連線,並將網頁顯示在uiwebview中
// 關閉連線

close(self.clientsocket);

// 擷取響應頭,只保留響應體, 響應頭結束的標識 \r\n\r\n

// 找指定字串所在的範圍,從它之後的第乙個位置開始擷取字串

nsrange range = [response rangeofstring:@"\r\n\r\n"];

// 擷取響應體

nsstring *html = [response substringfromindex:range.length + range.location];

// baseurl為html依賴的外部檔案所在的位址

[self.webview loadhtmlstring:html baseurl:[nsurl urlwithstring:@""]];

5. 完成第四步之後,返回的網頁是pc版的

要想使得返回的網頁是手機版的,需要在新增請求頭時新增"user-agent"這個請求頭,將第2步的請求頭內容更改為

// 模擬構造http請求頭

nslog(@"%@", request);

6. 完成**
//

// viewcontroller.m

//// created by mazaiting on 18/1/3.

//#import "viewcontroller.h"

#import #import #import @inte***ce viewcontroller ()

@property (weak, nonatomic) iboutlet uiwebview *webview;

@property (nonatomic, assign) int clientsocket;

@end

@implementation viewcontroller

- (void)viewdidload

nslog(@"連線成功");

// 模擬構造http請求頭

nslog(@"%@", request);

// 伺服器返回的響應頭 響應體

nsstring *response = [self sendandrecv:request];

nslog(@"返回的資料: %@", response);

// 關閉連線

close(self.clientsocket);

// 擷取響應頭,只保留響應體, 響應頭結束的標識 \r\n\r\n

// 找指定字串所在的範圍,從它之後的第乙個位置開始擷取字串

nsrange range = [response rangeofstring:@"\r\n\r\n"];

// 擷取響應體

nsstring *html = [response substringfromindex:range.length + range.location];

// baseurl為html依賴的外部檔案所在的位址

[self.webview loadhtmlstring:html baseurl:[nsurl urlwithstring:@""]];

}// 連線伺服器

- (bool)connectip:(nsstring *)ip port:(int)port else

}// 傳送和接收資料

- (nsstring *) sendandrecv:(nsstring *)sendmsg

nsstring *recvmsg = [[nsstring alloc] initwithdata:datas encoding:nsutf8stringencoding];

return recvmsg;

}- (void)didreceivememorywarning

- (bool)prefersstatusbarhidden

@end

iOS 使用Socket模擬手機訪問百度

bool result self connectip 220.181.111.188 port 80 if result nslog 連線成功 連線伺服器 bool connectip nsstring ip port int port else 2.構造請求頭 模擬構造http請求頭 nslog ...

使用ios自帶的socket

ios自帶乙個小的cfsocket庫,可以解決簡單的socket連線需求 void connect socket cfsocketcreate kcfallocatordefault,pf inet,sock stream,ipproto tcp,kcfsocketconnectcallback,型...

IOS 使用網域名稱進行Socket連線

cocos2d開發網 cocos2dev.com,謝謝!專案中用到了socket連線,由於我使用的boost,而boost的建立連線是只能傳ip位址的,而我伺服器位址是網域名稱,所以就要將網域名稱轉到ip。看了下 其實也挺簡單的。server address server domain hosten...