您的位置:首页 > 理论基础 > 计算机网络

IOS 网络浅析-(四 get&post)

2016-03-17 22:05 357 查看
网络请求默认是get

网络请求有很多种:GET查 POST改 PUT增 DELETE删 HEAD

在平时开发中主要用的 是 get 和 post.

get 获得数据 (获取用户信息)

get 请求是没有长度限制的,真正的长度限制是浏览器做的,限制长度一般2k

get 请求是有缓存的,get 有幂等的算法

get http://localhost/login.php?username=xubaoaichiyu&password=123456

请求参数暴露在url里

get请求参数格式:

?后是请求参数

参数名 = 参数值

& 连接两个参数的

post 添加,修改数据 (上传或修改用户信息)

post 请求是没有缓存的

http://localhost/login.php

post 也没有长度限制,一般控制2M以内

post 请求参数不会暴漏在外面 ,不会暴漏敏感信息

请求是有:请求头header,请求体boby(post参数是放在请求体里的)

get代码如下:

//
//  ViewController.m
//  CX-get
//
//  Created by ma c on 16/3/17.
//  Copyright © 2016年 xubaoaichiyu. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

//使用get请求,获取接口

NSString * String = @"http://localhost/login.php";

//拼接参数
NSString * urlString = [NSString stringWithFormat:@"%@?username=xubaoaichiyu&password=123456",String];

//如果有中文进行转码

urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL * url = [NSURL URLWithString:urlString];

NSURLRequest * request = [[NSURLRequest alloc]initWithURL:url cachePolicy:0 timeoutInterval:15];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {

NSString * string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

NSLog(@"%@",string);

}];

}

@end


post:

//
//  ViewController.m
//  CX-post
//
//  Created by ma c on 16/3/17.
//  Copyright © 2016年 xubaoaichiyu. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

//使用post请求
//获取接口
NSString * string = @"http://localhost/login.php";

//中文转码
string = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL * url = [NSURL URLWithString:string];

//可变请求
NSMutableURLRequest * requst = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:0 timeoutInterval:15];

//设置传输方式

requst.HTTPMethod = @"POST";

NSString * bodyString = [NSString stringWithFormat:@"username=xubaoaichiyu&password=123456"];

//设置请求体

requst.HTTPBody = [bodyString dataUsingEncoding:NSUTF8StringEncoding];

[NSURLConnection sendAsynchronousRequest:requst queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {

NSString * string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

NSLog(@"%@",string);

}];

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: