在iOS中,常见的发送HTTP请求的方案有

苹果原生(自带)

  1. NSURLConnection:用法简单,最古老最经典的一种方案
  2. NSURLSession:功能比NSURLConnection更加强大,推荐使用这种技术(2013年推出)
  3. CFNetwork:NSURL的底层,纯C语言

第三方框架

  1. ASIHttpRequest:外号:“HTTP终结者”,功能及其强大,早已不维护
  2. AFNETworking:简单易用,提供了基本够用的常用功能,维护和使用者居多
  3. MKNetworkKit:简单易用,来自印度,维护使用者少

建议

为了提高开发效率,企业开发用的基本是第三方框架

一.使用NSURLConnection

NSURLConnection常见的发送请求方法有以下几种
 
//同步请求
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error;
//异步请求:根据对服务器返回数据的处理方式的不同,又可以分为2种
//block回调
+ (void)sendAsynchronousRequest:(NSURLRequest*) request queue:(NSOperationQueue*) queue completionHandler:(void (^)(NSURLResponse* response, NSData* data, NSError* connectionError)) handler; //代理
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate;
+ (NSURLConnection*)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate;
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately;

代理相关的方法

#pragma mark -NSURLConnectionDelegate - begin

/**
请求失败(比如请求超时)
*/
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { } /**
接收到服务器的响应
*/
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"didReceiverResponse");
//初始化
self.responseData = [NSMutableData data];
} /**
接收到服务器的数据(如果数据量比较大,这个方法会调用多次)
*/
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"didReceiveData - %zd",data.length);
//拼接
[self.responseData appendData:data];
} /**
服务器的数据成功,接收完毕
*/
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"connectionDidFinishLoading");
//显示数据
NSString *str = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
NSLog(@"%@",str); }

二.使用NSURLSession

使用NSURLSession对象创建Task,然后执行Task

1.使用NSURLSessionDataTask

post请求

- (void)post {

    //获取NSURLSession对象
NSURLSession *session = [NSURLSession sharedSession]; //创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion_01.png"]];
request.HTTPMethod = @"POST";
request.HTTPBody = [@"username=520it&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding]; //创建任务
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}]; //启动任务
[task resume]; }

get请求

- (void)get {
NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *task = [session dataTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=123"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]); }]; //启动
[task resume];
}

代理方法

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];

    NSURLSessionDataTask *task = [session dataTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=123"]];

    //启动
[task resume];
} #pragma mark -<NSURLSessionDataDelegate> /**
* 1.接收到服务器的响应
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
NSLog(@"----%s----",__func__); //允许处理服务器的响应
completionHandler(NSURLSessionResponseAllow);
} /**
* 2.接收到服务器的数据(可能会被调用多次)
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
NSLog(@"----%s----",__func__);
} /**
* 3.请求成功或者失败(如果失败,error有值)
*/
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
NSLog(@"----%s----",__func__);
}

二.使用AFNetworking框架

网址:https://github.com/AFNetworking/AFNetworking

AFHTTPRequestOperationManager内部包装了NSURLConnection

- (void)get {
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; NSDictionary *params = @{
@"username" : @"520it",
@"pwd" : @"520it"
}; [mgr GET:@"http://120.25.226.186:32812/login" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"请求成功----%@",[responseObject class]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"请求失败----%@",error);
}];
}

AFHTTPSessionManager内部包装了NSURLSession

- (void)get2 {

    //AFHTTPSessionManager内部包装了NSURLSession
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager]; NSDictionary *params = @{
@"username" : @"520it",
@"pwd" : @"520it"
}; [mgr GET:@"http://120.25.226.186:32812/login" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(@"请求成功----%@",[responseObject class]); } failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"请求失败----%@",error);
}];
}

AFN这个框架默认使用了JSON解析器,如果服务器返回的是XML格式的

你需要将框架中的解析器换成XML解析器

    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];

    //responseSerializer 用来解析服务器返回的数据
//告诉AFN 以XML形式解析服务器返回的数据
mgr.responseSerializer = [AFXMLParserResponseSerializer serializer];

iOS中发送HTTP请求的方案的更多相关文章

  1. Vue中发送ajax请求——axios使用详解

    axios 基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 node.js 中使用 功能特性 在浏览器中发送 XMLHttpRequests 请求 在 node.js 中发送 htt ...

  2. IE6—在链接click事件的响应函数中发送jsonp请求不生效

    $("#link").click(function(){     $.ajax({         type: 'GET',         dataType: 'jsonp', ...

  3. 如何在WinForm中发送HTTP请求

    如何在WinForm中请求发送HTTP 手工发送HTTP请求主要是调用 System.Net的HttpWebResponse方法 手工发送HTTP的GET请 求: string strURL = &q ...

  4. IOS中DES与MD5加密方案

      0 2 项目中用的的加密算法,因为要和安卓版的适配,中间遇到许多麻烦. MD5算法和DES算法是常见的两种加密算法. MD5:MD5是一种不可逆的加密算法,按我的理解,所谓不可逆,就是不能解密,那 ...

  5. golang中发送http请求的几种常见情况

    整理一下golang中各种http的发送方式 方式一 使用http.Newrequest 先生成http.client -> 再生成 http.request -> 之后提交请求:clie ...

  6. iOS中几种数据持久化方案

    概论 所谓的持久化,就是将数据保存到硬盘中,使得在应用程序或机器重启后可以继续访问之前保存的数据.在iOS开发中,有很多数据持久化的方案,接下来我将尝试着介绍一下5种方案: plist文件(属性列表) ...

  7. rails中发送ajax请求

    最近在写一个blog系统练练手,遇到一个一个问题,用户添加评论的时候想发送ajax请求,但是rails里的ajax和Python中的不太一样,Python中的ajax是用js,jquery实现的和ra ...

  8. iOS中几种数据持久化方案:我要永远地记住你!

    http://www.cocoachina.com/ios/20150720/12610.html 作者:@翁呀伟呀 授权本站转载 概论 所谓的持久化,就是将数据保存到硬盘中,使得在应用程序或机器重启 ...

  9. java中发送http请求的方法

    package org.jeecgframework.test.demo; import java.io.BufferedReader; import java.io.FileOutputStream ...

随机推荐

  1. Vim 插件之 NERDTree

    设置快键键 编辑 .vimrc 添加以下内容后,可以使用 ctrl + n 来开关 NERDTree 插件. map <silent> <C-n> :NERDTreeToggl ...

  2. 介绍cms

    在这篇文章中,我们先来定义下什么是CMS(Content Management System)系统,在网站中它是如何帮你来变更内容的. 最后我将展示如何登录Umbraco系统. 简单来说CMS是一个系 ...

  3. 斜堆(一)之 C语言的实现

    概要 本章介绍斜堆.和以往一样,本文会先对斜堆的理论知识进行简单介绍,然后给出C语言的实现.后续再分别给出C++和Java版本的实现:实现的语言虽不同,但是原理如出一辙,选择其中之一进行了解即可.若文 ...

  4. Network - 工具列表

    Tcpdump homepage - tcpdump wiki - tcpdump Wireshark homepage - wireshark wiki - wireshark Fiddler ho ...

  5. Java向前引用容易出错的地方

    所谓向前引用,就是在定义类.接口.方法.变量之前使用它们,例如, class MyClass { void method() { System.out.println(myvar); } String ...

  6. 复利程序(c语言)(张俊毅 周修文)

    因为之前发烧一直没有了解这个 所以最近才补上 分数扣了就扣了 补上先 单元测试迟点更 #include<stdio.h> #include <math.h> #include ...

  7. ompparticles.cpp:(.text+0x322): undefined reference to `omp_set_num_threads'

    参考 http://www.code-by.org/viewtopic.php?f=54&t=163

  8. SQL Server 文件和文件组

    文件和文件组简介 在SQL Server中,数据库在硬盘上的存储方式和普通文件在Windows中的存储方式没有什么不同,仅仅是几个文件而已.SQL Server通过管理逻辑上的文件组的方式来管理文件. ...

  9. js不间断滚动

    CSS ul, li { margin: 0; padding: 0; } #scrollDiv { width: 300px; height: 25px; line-height: 25px; bo ...

  10. Html5学习笔记(1)

    1.figure\figcaption||detail\summary||mark学习笔记 效果图 代码为: <!DOCTYPE html> <html> <head&g ...