網頁

2012年1月6日 星期五

iOS學習_利用POST方法取得Server資訊(以NSURLConnection)

如果要做關於網路的應用,就必須要與伺服器溝通,所以串接HTTP要求或是WebService都是必測功能,本篇先以POST方法來傳遞要求並取得伺服器回應。

1. 建立以POST方法回應的頁面(以asp.net c#為例),內容很單純:接收兩個參數,並回傳一個json字串。

//於page_Load內
string tempName1 = Page.Request.Form["name"];
string tempName2 = Page.Request.Form["name2"];
Page.Response.Write("[{\"name\":\"" + tempName1 + "\"},{\"name:\"" + tempName2 + "\"}]");
Page.Response.End();


2. h檔,定義要接收結果的NSMutableData,並定義一個執行post的方法。

@interface AppDelegate : UIResponder <UIApplicationDelegate>{
NSMutableData *postResponseData;
}
-(void)doPostRequest;


3. m檔,以非同步方式,送出POST要求,並顯示回傳結果。

//a. 初始化NSMutableData,並執行doPostRequest。
-(void)initApp
{
postResponseData = [[NSMutableData alloc] init];
[self doPostRequest];
}
//b. 釋放該釋放的NSMutableData
- (void)dealloc
{
[postResponseData release];
[_window release];
[super dealloc];
}
//c. 於didFinishLaunchingWithOptions執行initApp
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self initApp];
[self.window makeKeyAndVisible];
return YES;
}
//d. 撰寫doPostRequest方法
-(void)doPostRequest
{
//第一步驟所建立的頁面url
NSString *urlPath = @"第一步驟所建立的頁面url/SendInfo.aspx";
//將NSString轉為NSURL
NSURL *url = [NSURL URLWithString:urlPath];
//因為要修改封包所以使用NSMutableURLRequest
NSMutableURLRequest *urlReq = [NSMutableURLRequest requestWithURL:url];
//指定封包方式
[urlReq setHTTPMethod:@"POST"];
//指定HTTP表頭
[urlReq setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
//產生封包內容,name=iphone.pdf&name2=b.jpg為送出的參數
NSString *requertString = @"name=iphone.pdf&name2=b.jpg";
NSData *requertBody = [NSData dataWithBytes:[requertString UTF8String] length:[requertString length]];
[urlReq setHTTPBody:requertBody];
//利用非同步方法送出要求
[[NSURLConnection alloc] initWithRequest:urlReq delegate:self];
}


4. m檔,撰寫NSURLConnection的delegate,共三個分別為:didReceiveResponse(第一次取得回應時,用於清空內容),didReceiveData(接收到資訊時,用於進度管理),connectionDidFinishLoading(完全取得資料時,用於程式後續處理)

//e. 撰寫NSURLConnection的delegate
//第一次回應時觸發
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[postResponseData setLength:0];
}
//取得資料時觸發
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[postResponseData appendData:data];
}
//資料取得完成後觸發
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *jsonString = [[NSString alloc] initWithData:postResponseData encoding:NSUTF8StringEncoding];
NSLog(@"json:%@",jsonString);
NSArray *names = [jsonString JSONValue];
NSLog(@"You get %d names" , [names count]);
for (int i = 0; i < [names count]; i++)
{
NSLog(@"name: %@" , [[names objectAtIndex:i]objectForKey:@"name"]);
}
}

*於connectionDidFinishLoading有使用json轉換的相關lib(SBJson),若沒使用可直接秀出NSString來看結果。

如果頁面回傳資料是從資料庫撈取,將上述的names放入UITableView就可以呈現一個單純又非常重要的Web應用。

2 則留言:

Blackwaltz 提到...
作者已經移除這則留言。
Blackwaltz 提到...

感謝您的教學

張貼留言