HTTP请求的常见方法

HTTP请求的常见方法

  • GET
    • 所有参数拼接在URL后面,并且参数之间用&隔开
    • 没有请求体
    • 一般用来查询数据
  • POST
    • 所有参数都放在请求体
    • 一般用来修改、增加、删除数据

创建HTTP请求

  • GET
// 请求路径
NSString *urlString = @"http://520it.com?name=张三&pwd=123";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

// 创建URL
NSURL *url = [NSURL URLWithString:urlString];

// 创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

// 设置请求方法(默认就是GET请求)
request.HTTPMethod = @"GET";
  • POST
// 请求路径
NSString *urlString = @"http://520it.com/图片";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

// 创建URL
NSURL *url = [NSURL URLWithString:urlString];

// 创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

// 设置请求方法
request.HTTPMethod = @"POST";

// 设置请求体
request.HTTPBody = [@"name=张三&pwd=123" dataUsingEncoding:NSUTF8StringEncoding];

使用NSURLConnection发送HTTP请求

发送同步请求

+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error;
// 这个方法是阻塞式的,会在当前线程发送请求
// 当服务器的数据完全返回时,这个方法才会返回,代码才会继续往下执行

发送异步请求-block

+ (void)sendAsynchronousRequest:(NSURLRequest*) request
                          queue:(NSOperationQueue*) queue
              completionHandler:(void (^)(NSURLResponse* response, NSData* data, NSError* connectionError)) handler;
// 会自动开启一个子线程去发送请求
// 当请求完毕(成功\失败),会自动调用handler这个block
// handler这个block会放到queue这个队列中执行

发送异步请求-delegate

  • 创建NSURLConnection对象
// startImmediately==YES,创建完毕后,自动发送异步请求
- (instancetype)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately;
- (instancetype)initWithRequest:(NSURLRequest *)request delegate:(id)delegate; // 创建完毕后,自动发送异步请求
+ (NSURLConnection*)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate; // 创建完毕后,自动发送异步请求
  • 发送请求
[connection start];
  • 遵守NSURLConnectionDataDelegate协议,实现协议中的代理方法
// 当接收到服务器的响应时就会调用
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;

// 每当接收到服务器返回的数据时就会调用1次(数据量大的时候,这个方法就会被调用多次)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;

// 当服务器的数据完全返回时调用(服务器的数据接收完毕)
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;

// 当请求失败的时候调用
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
  • 取消请求
[connection cancel];

NSString和NSData的互相转换

  • NSString -> NSData
NSData *data = [@"520it.com" dataUsingEncoding:NSUTF8StringEncoding];
  • NSData -> NSString
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  //发送请求给服务器,加载右侧的数据
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"a"] = @"list";
        params[@"c"] = @"subscribe";
        params[@"category_id"] =@(c.id);
        [[AFHTTPSessionManager manager] GET:@"http://api.budejie.com/api/api_open.php" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
            //字典转模型数组
           NSArray *users = [XJQRecommendUser objectArrayWithKeyValuesArray:responseObject[@"list"]];

            //添加当前类别对应的用户组
            [c.users addObjectsFromArray:users];
            //刷新表格
            [self.detailVC reloadData];

        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"加载数据失败"];
        }];

推荐阅读更多精彩内容

  • HTTP请求的常见方法 GET所有参数拼接在URL后面,并且参数之间用&隔开比如http://520it.com?...
    牧马人_hlc阅读 749评论 0 3
  • HTTP请求的常见方法 GET所有参数拼接在URL后面,并且参数之间用&隔开比如http://http://www...
    fwlong阅读 268评论 0 0
  • iOS开发系列--网络开发 概览 大部分应用程序都或多或少会牵扯到网络开发,例如说新浪微博、微信等,这些应用本身可...
    lichengjin阅读 3,280评论 2 7
  • 如何找到服务器 URL URL中常见的协议 - HTTP - 超文本传输协议,访问的是远程的网络资源,格式是htt...
    Hevin_Chen阅读 1,047评论 0 1
  • 人生如草,如草之平凡,只要有雨露和阳光就有她们的生命的存在;人生如草,如草的坚韧,无论命运怎样折腾,小草的生命永远...
    水乡醉客阅读 536评论 2 5