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

1.Get方法

1.1 使用NSMutableURLRequest

view plaincopy to clipboardprint?
NSURL* url = [NSURL URLWithString:@"http://aminby.net"]; 
NSMutableURLRequest* request = [NSMutableURLRequest new]; 
[request setURL:url]; 
[request setHTTPMethod:@"GET"]; 
NSHTTPURLRequest* response; 
NSData* data = [NSURLConnection sendSynchronousRequest:request 
              returningResponse:&response error:nil]; 
[NSString* strRet = [[NSString alloc] initWithData:data encoding:NSUTF8String]; 
NSLog(strRet); 
[strRet release]; 
1.2 使用NSString

view plaincopy to clipboardprint?
[NSString stringWithContentsOfURL:(NSURL *)url 
            encoding:(NSStringEncoding)enc error:(NSError **)error]; 
// 或者 
[NSString stringWithContentsOfURL:(NSURL *)url]; 
1.3 使用NSData

view plaincopy to clipboardprint?
// options有两个枚举,NSMappedRead这个不懂, NSUncachedRead是不缓存 
[NSData dataWithContentsOfURL:(NSURL *)url 
        options:(NSUInteger)readOptionsMask 
        error:(NSError **)errorPtr] 
//  或者 
[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?
NSURL* url = [NSURL URLWithString:@"http://aminby.net"]; 
NSMutableURLRequest*  request = [NSMutableURLRequest new]; 
[request setURL:url]; 
[request  setHTTPMethod:@"GET"]; 
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
[request setHTTPBody:@"some param"]; 
NSHTTPURLRequest* response; 
NSData* data =  [NSURLConnection sendSynchronousRequest:request 
         returningResponse:&response error:nil]; 
[NSString* strRet =  [[NSString alloc] initWithData:data encoding:NSUTF8String]; 
NSLog(strRet); 
[strRet  release];   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值