iOS使用ASIHttpRequest+Json与服务器段脚本进行登陆验证

ASIHttpRequest的配置可参见:http://blog.csdn.net/zengraoli/article/details/12882167

核心代码如下:

-(void)initData
{
    NSString *userName = @"test@111.com";
    NSString *pwd = @"123456";
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:userName forKey:@"name"];
    [params setObject:pwd forKey:@"pwd"];
    
    NSString *postURL=[self createPostURL:params];
    [params release];
    
    NSLog (@"postURL is :%@", postURL);
    
    NSString *baseurl=@"Login.php";
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@?%@",host_url,baseurl,postURL]];
	[self setRequest:[ASIHTTPRequest requestWithURL:url]];
	[_request addRequestHeader:@"User-Agent" value:@"ASIHTTPRequest"];
	[_request startSynchronous];
    
    //显示网络请求信息在status bar上
    [ASIHTTPRequest setShouldUpdateNetworkActivityIndicator:YES];
    
    if (_request)
    {
        if ([_request error])
        {
            NSLog(@"error");
        }
        else if ([_request responseString])
        {
            NSString *result = [_request responseString];
            NSLog(@"%@",result);
            NSDictionary *mydict = [result JSONValue];
            
            NSLog(@"login successed");
            
            describeDictionary(mydict);
        }
    }
    else
    {
        NSLog(@"request is nil.");
    }
}

void describeDictionary(NSDictionary *dict)
{
    NSArray *keys;
    int i, count;
    id key, value;
    
    keys = [dict allKeys];
    count = [keys count];
    for (i = 0; i < count; i++)
    {
        key = [keys objectAtIndex: i];
        value = [dict objectForKey: key];
        NSLog (@"Key: %@ for value: %@", key, value);
    }
}


可以看到这些代码得到的回复:


对代码的初步解析:

1、首先用两个NSString构建NSMutableDictionary类型的字典

2、拼接连接字符串

3、加上请求的头,等待服务器的回应

4、如果服务器有返回,则_request不为nil,并且不为error(过滤掉诸如远程服务器没打开之类的错误)

5、解析responseString即回应的字符串

6、Json数据转换成NSString

NSString *result = [_request responseString];

7、从 Json数据中把数据读取到字典中

8、显示出来

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值