GET和POST请求

#pragma mark----创建 GET请求
- (void)getMethod{
    NSString *username = @"123456";

    NSString *password = @"123456";

    //用户名和密码在同一个url(用户名和密码不能为中文,有中文需要转译)

    NSString *string = [NSString stringWithFormat:@"http://10.10.161.56/login.php?username=%@&password=%@",username, password];

    //如果有汉字,转译成二进制字符串

    string = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSURL *url = [NSURL URLWithString:string];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //创建连接
    [NSURLConnection sendAsynchronousRequest:request queue:0 completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        //请求结束, 获得想请求的数据
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
        NSLog(@"%@", dict);
    }];

}


#pragma mark----创建POST请求
- (void)postMethod{

    //url中不存在用户名和密码

    NSString *string = @"http://10.10.161.8/login.php";
    NSURL *url = [NSURL URLWithString:string];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置网络请求方式(默认为GET)
    request.HTTPMethod = @"POST";

    NSString *username = @"张三";
    NSString *userpassword = @"123456";
    NSString *bodyStr = [NSString stringWithFormat:@"username=%@&userpassword=%@",username, userpassword];
    //添加请求体
    request.HTTPBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [NSURLConnection sendAsynchronousRequest:request queue:0 completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        //完成请求
        NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        NSLog(@"%@",connectionError);
    }];
    NSLog(@"11111");
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值