现在的位置: 首页 > 综合 > 正文

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

2018年08月03日 ⁄ 综合 ⁄ 共 2095字 ⁄ 字号 评论关闭

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

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

 

1.Get方法

 

1.1

使用NSMutableURLRequest view plaincopy to clipboardprint?

 

 

C代码  收藏代码
  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?

 

Java代码  收藏代码
  1. [NSString stringWithContentsOfURL:(NSURL *)url  encoding:(NSStringEncoding)enc error:(NSError **)error];  
  2. / 或者  
  3. [NSString stringWithContentsOfURL:(NSURL *)url];  
  4. [NSString stringWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error]; // 或者 [NSString stringWithContentsOfURL:(NSURL *)url];  

 

 

1.3 使用NSData view plaincopy to clipboardprint?

 

 

C代码  收藏代码
  1. [NSData dataWithContentsOfURL:(NSURL *)url];  
  2. // options有两个枚举,NSMappedRead这个不懂, NSUncachedRead是不缓存  
  3. [NSData dataWithContentsOfURL:(NSURL *)url options:(NSUInteger)readOptionsMask error:(NSError **)errorPtr]   

 

 

 

1.2和1.3的方法是缺点是没办法知道response的status,一般是返回200-299之间的数值代表请求成功.

我们可以依照这个code来做数据处理, 如果对地址存在很有把握,就可以使用后两种简单的GET方法.

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

 

2.Post方法

 

2.1

使用NSMutableURLRequest view plaincopy to clipboardprint?

C代码  收藏代码
  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 returningResponse:&response error:nil];  
  9. [NSString* strRet = [[NSString alloc] initWithData:data encoding:NSUTF8String];  
  10. NSLog(strRet);  
  11. [strRet release];  

 

 

转载地址:

http://aminby.net/2010/07/iphone-develop-how-to-send-http-request/

抱歉!评论已关闭.