关于IOS网络连接部分,服务器端使用的是JAVA,采用HTTP发送请求,数据传输格式是JSON
基本的思路就是,在ios客户端创建一个异步的HTTP请求,服务器端接受到请求后,处理,将返回来得数据用JSON 进行封装。IOS端接受到返回来的数据,
进行数据解析,
然后返回到主线程刷新界面UI上的数据
详细的可以参考技术博客:http://www.cnblogs.com/kenshincui/p/4042190.html
下面看IOS端网络连接的部分代码
//访问服务器端的url字符串
NSString *
strURL=[[NSString alloc]initWithFormat:@"
http://ip:8080/DemoTest/LoginCheck"];
//将字符串转换成连接的URL
NSURL *
url=[NSURL URLWithString:
strURL];
//初始化HTTP请求
NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:
url cachePolicy:0 timeoutInterval:5.0f];
//设定请求的方法为POST方法
[request setHTTPMethod:@"POST"];
//参数字符串
NSString *bodyDateStr=[NSString stringWithFormat:@"phone=%@&password=%@",cellPhone,password];
NSData* bodyDate=[bodyDateStr dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:bodyDate];
//初始化一个进程
NSOperationQueue *queue=[NSOperationQueue mainQueue];
//发送一个异步的请求
[NSURLConnection sendAsynchronousRequest:
request queue:
queue completionHandler:^(NSURLResponse *response, NSData *
data, NSError *
connectionError) {
if (!connectionError) {
NSDictionary* dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
if(dict==nil)
{
UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示信息" message:@"用户名或密码错误" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil];
[alertView show];
}
else
{ //当拿到了返回数据,需要将数据加载到UI界面上
NSString *uid=dict[@"ID"];
NSString *phone=dict[@"phone"];
//由于是异步请求,所以需要返回到主线程,刷新界面UI上的数据
[self performSelectorOnMainThread:@selector(refreshUI:) withObject:dic waitUntilDone:YES];
}
}
}
else{
[queue addOperationWithBlock:^{
}];
return ;
}
}];
//主进程刷新界面
-(void)refreshUI:(NSDictionary*)dic{
self.carNumber.text=[dic[@"carNumber"] stringValue];
self.goodsNumber.text=[dic[@"goodsNumber"] stringValue];
}