只需在 ##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];
}
- (IBAction)getPhoneNumberMessage:(id)sender {
NSString *str = [NSString stringWithFormat:TEST_URL,self.myNumberTF.text];
NSURL *url = [NSURL URLWithString:str];
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
[NSURLConnection connectionWithRequest:request delegate:self];
}
- (IBAction)postPhoneNumberMessage:(id)sender {
NSURL *url = [NSURL URLWithString:POST_URL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
[request setHTTPMethod:@"POST"];
NSString *str = [NSString stringWithFormat:@"mobileCode=%@&userID=",self.myNumberTF.text];
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
NSData *myDatas = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
self.myMessageTV.text = [[NSString alloc]initWithData:myDatas encoding:NSUTF8StringEncoding];
}
#pragma mark - 实现NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
_myData = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[_myData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
self.myMessageTV.text = [[NSString alloc]initWithData:_myData encoding:NSUTF8StringEncoding];
}