iOS中HTTP请求小结

iOS SDK为HTTP请求提供了同步异步请求两种不同的API,而且可以使用Get或Post等请求方法。

1、发送 “同步、Get” 请求

- (void)startRequest

{

  NSString *strUrl = [[NSString alloc]
initWithFormat:@"http://iosbook3.com/service/mynotes/webservice.php?email=%@&type=%@&action=%@",@"[email protected]",@"JSON",@"query"];
  【1】

  NSURL *url = [NSURL URLWithString:[strUrl
URLEncodedString]];            
              【2】

  NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];  
                     
   【3】

  NSData *data = [NSURLConnection
sendSynchronousRequest:request  returningReponse:nil
 error:nil];   【4】

  NSLog(@"请求完成....");

  NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments error:nil];

  ........

}

【1】:指定请求的URL。请求的参数全部暴露在URL后面(说明URL不包括请求参数),这是Get请求方法的特定

【2】:创建NSURL对象。[strUrl URLEncodedString]将strUrl字符串转换为URL字符串,在Internet传输的时候,URL中不能有中文等特殊字符,使用URLEncodedString就是把这些特殊字符转化为有百分号的URL编码。

【3】:创建NSURLRequest对象,可以使用更为复杂的形式initWithURL:cachePolicy:timeoutInterval设置缓存策略和超时时长。

【4】:使用NSURLConnection的sendSynchronousRequest:
 returningReponse:
error:同步方法进行请求,返回NSData类型的数据。所谓同步方法就是请求过程中线程阻塞到这里,直到服务器应答返回回来为止。

2、发送“异步、Get”请求

异步请求会使用NSURLConnection委托协议NSURLConnectionDelegate。

NSURLConnectionDelegate协议的方法有:

connection:didReciveData:请求成功,开始接收数据,如果数据量很多,可能会被多次调用

connection:didFailWithError:加载数据出现异常

connectionDidFinishLoading:成功完成加载数据,在connection:didReciveData:方法之后执行。

- (void)startRequest

{

  NSString *strUrl = [[NSString alloc]
initWithFormat:@"http://iosbook3.com/service/mynotes/webservice.php?email=%@&type=%@&action=%@",@"[email protected]",@"JSON",@"query"];

  NSURL *url = [NSURL
URLWithString:[strUrl URLEncodedString]];

  NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

  NSURLConnection *connection= [[NSURLConnection alloc]
initWithRequest:request

delegate:self ];

  if (connection)

  {

    _datas = [[NSMutableData  alloc] init];

  }

}

#pragma mark - NSURLConnection代理方法

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData
*)data

{

  [_datas appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

  NSLog(@"请求完成....");

  NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments error:nil];

  。。。

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError
*)error

{

}

从上面两个Get请求方式可以看出:Get请求方式与同步请求还是异步请求无关。

3、发送“异步、Post”请求

使用Post方法请求的关键是:使用NSMutableURLRequest类替代NSURLRequest。

- (void)startRequest

{

  NSString *strUrl = [[NSString alloc]
initWithFormat:@"http://iosbook3.com/service/mynotes/webservice.php"];

  NSURL *url = [NSURL
URLWithString:[strUrl URLEncodedString]];

  // 准备请求体

  NSString *post = [NSString
stringWithFormat:@"email=%@&type=%@&action=%@",@"[email protected]",@"JSON",@"query"] ;

  NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
     【1】

  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

  [request setHTTPMethod:@"POST"];

  [request setHTTPBody:postData];      //
 HTTPBody部分是请求参数。

  NSURLConnection *connection= [[NSURLConnection alloc]
initWithRequest:request

delegate:self ];

  if (connection)

  {

    _datas = [[NSMutableData  alloc] init];

  }

}

【1】:将参数字符串转换成NSData类型,编码一定要采用UTF-8.

注:设置request请求头:

[ request  setValue
:@“application/soap+xml;charset=utf-8”
 forHTTPHeaderField:@"Content-Type" ] ;

时间: 2024-08-29 23:46:44

iOS中HTTP请求小结的相关文章

iOS中网络请求的使用(GET请求与POST请求)

GET&POST GET和POST是两种最常用的与服务器进行交互的HTTP方法 GET 语意是获取指定URL的资源. 将数据按照variable=value的形式,添加到action所指向的URL后面,并且两者只用“?”连接,各变量之间使用“&”连接. 貌似不安全,因为在传输过程中,数据被放在请求的URL中. 传输的数据量小,这主要是因为受URL长度限制. POST POST的语意说向指定URL的资源添加数据. 将数据放在数据体中,按照变量和值相对应的方式,传递到action所指向URL.

IOS中http请求的cookie查看,删除,添加

一直以为ios的http请求这块很简单应该不支持记录,保存,或者使用cookie,可是想当然归想当然,真用的时候,真研究了一下发现还真强大.经过一番的研究简单说一下我的理解:当你访问一个网站时,不管你愿意或者不愿意,NSURLRequest都会帮你主动记录下来你访问的站点设置的cookie,而且很负责任的,当你下次再访问这个站点时,NSURLRequest会拿着上次保存下来了的cookie继续去请求.这规律同样适用于ASIHTTPRequest.所以当你做一些基于认证的网络请求时,cookie不

iOS中的请求(GET请求,POST请求,同步请求,异步请求)

1.用到的一些第三方 PostTableViewController.m #import "PostTableViewController.h" @interface PostTableViewController () @property(nonatomic,retain) NSArray *dataArr; @end @implementation PostTableViewController - (void)viewDidLoad { [super viewDidLoad];

小结Android和iOS中LocalNotification

用Unity开发游戏,总难免要用到Native Development,比如Notification功能. 本文只对LocalNotification进行小结,iOS上RemoteNotification在此未讨论.(后面发现Unity已经把iOS部分给封装好了) Notification大致提供了两个功能:Register和Cancel,没找到Update的API,后来自己想了个Update的方法,就是先Cancel再Register. iOS: 1 //由于c#用long类型传递秒数,而lo

iOS中发送HTTP请求的方案

在iOS中,常见的发送HTTP请求的方案有 苹果原生(自带) NSURLConnection:用法简单,最古老最经典的一种方案 NSURLSession:功能比NSURLCOnnection更加强大,推荐使用这种技术(2013年推出) CFNetwork:NSURL的底层,纯C语言 第三方框架 ASIHttpRequest:外号:“HTTP终结者”,功能及其强大,早已不维护 AFNETworking:简单易用,提供了基本够用的常用功能,维护和使用者居多 MKNetworkKit:简单易用,来自印

ios中封装网络请求类

ios中封装网络请求类 #import "JSNetWork.h" //asiHttpRequest #import "ASIFormDataRequest.h" //xml 的解析 #import "UseXmlParser.h" //判断是否联网 #import "Reachability.h" //sbJson,判断json的解析 #import "JSON.h" @implementation JS

ios中的ASIHTTPRequest的同步请求和异步请求

1.首先加入ASI开源库 2. WebImageView.h #import <UIKit/UIKit.h> #import "ASIHTTPRequest.h" @interface WebImageView :UIImageView<ASIHTTPRequestDelegate> - (void)setImageURL:(NSURL *)url; @end WebImageView.m #import "WebImageView.h" #

iOS中使用block进行网络请求回调

iOS中使用block进行网络请求回调 HttpRequest.h // // HttpRequest.h // UseBlockCallBack // // Created by Michael on 2/13/14. // Copyright (c) 2014 EIMS. All rights reserved. // #import <Foundation/Foundation.h> typedef void (^FinishBlock)(NSString *dataString); @

**iOS发JSON请求中字符串加转义,返回的JSON去转义

iOS中使用NSSerialization把对象转为JSON字符串后,多出来反斜杠的问题 http://segmentfault.com/q/1010000000576646 NSDictionary *dic = @{@"url": @"http://..."}; NSLog(@"%@", dic); NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:N