HTTP请求的常见方法
GET
所有参数拼接在URL后面,并且参数之间用&隔开
比如http://520it.com?name=123&pwd=345传递了2个参数给服务器
name参数:123pwd参数:345没有请求体一般用来查询数据POST
所有参数都放在请求体中一般用来修改、增加、删除数据
创建HTTP请求
GET
NSString *urlString = @
"http://520it.com?name=张三&pwd=123";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [
NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request
.HTTPMethod = @
"GET";
POST
NSString *urlString = @
"http://520it.com/图片";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
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;
发送异步请求-delegate
创建NSURLConnection对象
- (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;
- (
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:@
"加载数据失败"];
}];
转载请注明原文地址: https://ju.6miu.com/read-1295033.html