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、显示出来