Iphone用http協議和服務器通信有兩種方式,一種是同步一種是異步的,所謂同步是指當客戶端調用post/get的方式的函數向服務器發出數據請求後,該函數不會直接返回,只有得到服務器響應或者請求時間timeout之後纔會返回繼續執行其它任務。異步採用回調的方式,即請求發送後,函數會立即返回,一旦服務器聯結成功操作系統會去觸發相應的回調進行相應的處理。這和window的消息處理機制一樣。
同步一般用於一次性操作,如判斷當前網絡是否可用等等。多的就不再一一介紹,在實現上面有兩點不同:
(1)在用NSURLConnect的時候一個調用同步函數一個調用了異步函數。
(2)異步的需要實現delegate的相關回調函數。
以下是參考代碼:
同步方式:
-(void)UpadaPost:(NSString *)strcontext URL:(NSString *)urlstr{
NSLog(urlstr);
NSLog(strcontext);
assert(strcontext != NULL);
assert(urlstr != NULL);
NSData*postData=[strcontextdataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlstr]];
[request setHTTPMethod:@"POST"]; [request setTimeoutInterval: 20];//setting timeout
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *respone;
NSError *error;
NSData*myReturn=[NSURLConnection sendSynchronousRequest:request returningResponse:&respone
error:error];
NSLog(@"%@", [[NSString alloc] initWithData:myReturn encoding:NSUTF8StringEncoding]);
}
異步方式:
-(void)UpadaPost:(NSString *)strcontext URL:(NSString *)urlstr{
NSLog(urlstr);
NSLog(strcontext);
assert(strcontext != NULL);
assert(urlstr != NULL);
NSData *postData = [strcontext dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlstr]];
[request setHTTPMethod:@"POST"]; [request setTimeoutInterval: 20];//setting timeout
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn)
{
NSLog(@"Connection success");
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[conn retain];
}
else
{
// inform the user that the download could not be made
}
}
#pargma mark------------------以下爲相應的回調函數-------------------------------
// 收到響應時, 會觸發
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// 注意這裏將NSURLResponse對象轉換成NSHTTPURLResponse對象才能去
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
if ([response respondsToSelector:@selector(allHeaderFields)]) {
NSDictionary *dictionary = [httpResponse allHeaderFields];
NSLog([dictionary description]);
NSLog(@"%d",[response statusCode]);
}
}
//鏈接錯誤
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
//[self performSelectorOnMainThread:@selector(httpConnectEnd) withObject:nil waitUntilDone:NO];
NSLog(@"%@",[error localizedDescription]);
}
// Called when a chunk of data has been downloaded.
//接收數據 每收到一次數據, 會調用一次
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Process the downloaded chunk of data.
NSLog(@"%d", [data length]);
//NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
//[self performSelectorOnMainThread:@selector(updateProgress) withObject:nil waitUntilDone:NO];
}
//接收結束
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"%@",connection);
//NSLog(@"%lld", received_);
//[self performSelectorOnMainThread:@selector(httpConnectEnd) withObject:nil waitUntilDone:NO];
// Set the condition which ends the run loop.
}
[提示]:
According to a post on the Apple developer forum, the minimum timeout interval for POST is 240 seconds. Any timeout interval shorter than that is ignored.
If you require a shorter timeout interval, use an async request along with a timer and call cancel on the NSURLConnection as needed.