Xcode自带get和post请求

景皓™

景皓™

发表于 2016-07-23 20:30:17
内容来源: 网络
get和post请求方法和区别。
GET
1.GET一般是获取服务器上的数据
2.GET方式是通过过url传递数据,效率高.
3.请求的数据在URL上,不安全.
4.GET请求的结果能够被浏览器缓存.
POST
1.POST一般是王服务器提交数据,病获取服务器返回的结果.
2.POST方式是通过过请求传输数据,效率低.
3.请求的数据用户看不到,相对安全.
4.POST请求不能被浏览器缓存.
- (void)get {
    NSString *name = @"张三";
    NSString *pwd = @"zhang";
    NSString *strUrl = [NSString stringWithFormat:@"http://127.0.0.1/php/login.php?username=%@&password=%@",name,pwd];
    //对汉字或者空格做百分号转义
    strUrl = [strUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    //当地址中出现空格或者汉字 url返回nil
    NSURL *url = [NSURL URLWithString:strUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError) {
            NSLog(@"连接错误 %@",connectionError);
            return;
        }
        //
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
        if (httpResponse.statusCode == 200 || httpResponse.statusCode == 304) {
            //解析数据
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
            NSLog(@"%@",dic);
            
        }else{
            NSLog(@"服务器内部错误");
        }
    }];
}


- (void)post {
    NSString *strUrl = @"http://127.0.0.1/php/login.php";
    
    NSURL *url = [NSURL URLWithString:strUrl];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //发送post请求
    request.HTTPMethod = @"post";
    //设置请求体
    NSString *body = @"username=123&password=abc";
    //把字符串转换成NSData对象
    request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError) {
            NSLog(@"连接错误 %@",connectionError);
            return;
        }
        
        //
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
        if (httpResponse.statusCode == 200 || httpResponse.statusCode == 304) {
            //解析数据
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
            NSLog(@"%@",dic);
        }else{
            NSLog(@"服务器内部错误");
        }
    }];
}
                            
相关帖子
用户评论
开源开发学习小组列表