手机号码归属地查询

这里写图片描述

只需在 ##ViewController.m##中实现以下代码,分为get和post请求,本文采用拖控件的方法实现

#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];
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值