NSURLConnection

本文详细介绍了iOS中使用NSURLRequest和NSURLConnection进行网络请求的方法,包括GET和POST请求的创建及JSON数据的发送,并提供了网络状态监控的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

常用类

NSURL:请求地址

 

NSURLRequest:一个NSURLRequest对象就代表一个请求,它包含的信息有

一个NSURL对象

请求方法、请求头、请求体

请求超时

… …

 

NSMutableURLRequest:NSURLRequest的子类

 

NSURLConnection

负责发送请求,建立客户端和服务器的连接

发送NSURLRequest的数据给服务器,并收集来自服务器的响应数据

 

使用NSURLConnection发送请求的步骤很简单

创建一个NSURL对象,设置请求路径

传入NSURL创建一个NSURLRequest对象,设置请求头和请求体

使用NSURLConnection发送NSURLRequest

 

 

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;

 

在startImmediately = NO的情况下,需要调用start方法开始发送请求

- (void)start;

 

成为NSURLConnection的代理,最好遵守NSURLConnectionDataDelegate协议

 

 

NSURLConnectionDataDelegate协议中的代理方法

开始接收到服务器的响应时调用

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;

 

接收到服务器返回的数据时调用(服务器返回的数据比较大时会调用多次)

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

 

服务器返回的数据完全接收完毕后调用

- (void)connectionDidFinishLoading:(NSURLConnection *)connection;

 

请求出错时调用(比如请求超时)

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

 

NSMutableURLRequest是NSURLRequest的子类,常用方法有

设置请求超时等待时间(超过这个时间就算超时,请求失败)

- (void)setTimeoutInterval:(NSTimeInterval)seconds;

 

设置请求方法(比如GET和POST)

- (void)setHTTPMethod:(NSString *)method;

 

设置请求体

- (void)setHTTPBody:(NSData *)data;

 

设置请求头

- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;

 

创建GET请求

NSString *urlStr = [@"http://192.168.1.102:8080/MJServer/login?username=123&pwd=123" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL *url = [NSURL URLWithString:urlStr];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

 

创建POST请求

NSString *urlStr = @"http://192.168.1.102:8080/MJServer/login";

NSURL *url = [NSURL URLWithString:urlStr];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

request.HTTPMethod = @"POST";

// 请求体

NSString *bodyStr = @"username=123&pwd=123";

request.HTTPBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];

 

 

如何发送JSON给服务器

一定要使用POST请求

设置请求头

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

设置JSON数据为请求体

 

 

在网络应用中,需要对用户设备的网络状态进行实时监控,目的是

让用户了解自己的网络状态,防止一些误会(比如怪应用无能)

根据用户的网络状态进行智能处理,节省用户流量,提高用户体验

WIFI\3G网络:自动下载高清图片

低速网络:只下载缩略图

没有网络:只显示离线的缓存数据

 

苹果官方提供了一个叫Reachability的示例程序,便于开发者检测网络状态

https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip

 

Reachability的使用步骤

添加框架SystemConfiguration.framework

 

 

添加源代码

 

包含头文件

#import "Reachability.h"

 

常见用法

// 是否WIFI

+ (BOOL) IsEnableWIFI {

    return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);

}

 

// 是否3G

+ (BOOL) IsEnable3G {

    return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);

}

 

[[NSNotificationCenter defaultCenter] addObserver:self

 selector:@selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];

self.netReachability = [Reachability reachabilityForInternetConnection];

[self.netReachability startNotifier];

 

- (void)dealloc

{

    [self.netReachability stopNotifier];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];

}

转载于:https://my.oschina.net/itcastBlogs/blog/684835

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值