#import "ViewController.h"
//服务器连接地址
#define TEST_URL @"http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode=%@&userID="
#define POST_URL @"http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo"
@interface ViewController ()<NSURLConnectionDataDelegate>
{
NSMutableData *_myData;//接受服务器端返回的数据
}
@property (weak, nonatomic) IBOutlet UITextField *myNumberTF;//手机号码输入框
@property (weak, nonatomic) IBOutlet UITextView *myMessageTV;//查询归属地后的信息展示框
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
//get请求
- (IBAction)getPhoneNumberMessage:(id)sender {
//1.准备好连接字符串
NSString *str = [NSString stringWithFormat:TEST_URL,self.myNumberTF.text];
//2.将字符串类型封装一个连接类型
NSURL *url = [NSURL URLWithString:str];
//3.将连接封装成请求对象
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
//4.get 请求 代理
[NSURLConnection connectionWithRequest:request delegate:self];
}
//post请求
- (IBAction)postPhoneNumberMessage:(id)sender {
//1.创建 URL 地址
NSURL *url = [NSURL URLWithString:POST_URL];
//2.封装一个请求对象
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
//3.设置请求方式
[request setHTTPMethod:@"POST"];
//设置需要传递的参数
//mobileCode=string&userID=string
//4.参数
NSString *str = [NSString stringWithFormat:@"mobileCode=%@&userID=",self.myNumberTF.text];
//5.转换格式
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
//6.设置需要传递的参数
[request setHTTPBody:data];
//7.sendSynchronousRequest :发送同步请求
NSData *myDatas = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//8.展示信息
self.myMessageTV.text = [[NSString alloc]initWithData:myDatas encoding:NSUTF8StringEncoding];
}
#pragma mark - 实现NSURLConnectionDataDelegate
//请求服务器成功后自动回调 执行一次
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
//初始化
_myData = [[NSMutableData alloc]init];
}
//成功读取服务器端数据后自动回调 执行多次
//appendData :附加参数
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
//拼接数据
[_myData appendData:data];
}
//请求结束后自动回调
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
//展示信息
self.myMessageTV.text = [[NSString alloc]initWithData:_myData encoding:NSUTF8StringEncoding];
}
因篇幅问题不能全部显示,请点此查看更多更全内容