发送Http请求(POST GET)的方法

来源:互联网 发布:vb回车触发事件 编辑:程序博客网 时间:2024/05/07 03:23

来源:代码人生(http://aminby.net/2010/07/iphone-develop-how-to-send-http-request/)

http://blog.csdn.net/ipromiseu/archive/2010/07/26/5767651.aspx

我们知道Http有Get和Post两种方法,我们分开说吧.

另注: 今天讲的方法是同步的请求, 异步的方法我还没试过, 不知道有没有使用异步的需求, 有的话于发上来和大家分享.

1.Get方法

1.1 使用NSMutableURLRequest

 

view plaincopy to clipboardprint?
  1. NSURL* url = [NSURL URLWithString:@"http://aminby.net"];    
  2. NSMutableURLRequest* request = [NSMutableURLRequest new];    
  3. [request setURL:url];    
  4. [request setHTTPMethod:@"GET"];    
  5. NSHTTPURLRequest* response;    
  6. NSData* data = [NSURLConnection sendSynchronousRequest:request    
  7.               returningResponse:&response error:nil];    
  8. [NSString* strRet = [[NSString alloc] initWithData:data encoding:NSUTF8String];    
  9. NSLog(strRet);    
  10. [strRet release];    
 

 

1.2 使用NSString

 

view plaincopy to clipboardprint?
  1. / options有两个枚举,NSMappedRead这个不懂, NSUncachedRead是不缓存    
  2. [NSData dataWithContentsOfURL:(NSURL *)url    
  3.         options:(NSUInteger)readOptionsMask    
  4.         error:(NSError **)errorPtr]    
  5. //  或者    
  6. [NSData dataWithContentsOfURL:(NSURL *)url];    
 

 

1.2和1.3的方法是缺点是没办法知道response的status,一般是返回200-299之间的数值代表请求成功.我们可以依照这个code来做数据处理, 如果对地址存在很有把握,就可以使用后两种简单的GET方法.

今天查了一下手册,发现NSArray NSDictionary 也有xxxxWithContentsOfURL的方法, 这两个我还没用过, 应该是跟NSData和NSString一样,但具体怎么用我还不清楚.

2.Post方法

2.1 使用NSMutableURLRequest

 

view plaincopy to clipboardprint?
  1. NSURL* url = [NSURL URLWithString:@"http://aminby.net"];    
  2. NSMutableURLRequest*  request = [NSMutableURLRequest new];    
  3. [request setURL:url];    
  4. [request  setHTTPMethod:@"GET"];    
  5. [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];    
  6. [request setHTTPBody:@"some param"];    
  7. NSHTTPURLRequest* response;    
  8. NSData* data =  [NSURLConnection sendSynchronousRequest:request    
  9.          returningResponse:&response error:nil];    
  10. [NSString* strRet =  [[NSString alloc] initWithData:data encoding:NSUTF8String];    
  11. NSLog(strRet);    
  12. [strRet  release];