iOS http 学习

时间:2018-09-02 03:59:11
【文件属性】:
文件名称:iOS http 学习
文件大小:56KB
文件格式:ZIP
更新时间:2018-09-02 03:59:11
iOS http 学习 简单的http demo - (IBAction)get_btn_touch_up_inside:(id)sender { //K1+车次+K2 NSString *url=[K1 stringByAppendingString:self.m_trainName.text]; url=[url stringByAppendingString:K2]; NSURL *urlRquest=[NSURL URLWithString:k4]; NSURLRequest *request=[NSURLRequest requestWithURL:urlRquest]; NSLog(@"get_begin");//开始get的方法发送数据最好写成GCD的方式 NSURLResponse *response=nil;//获取服务器的响应返回 NSError *error=nil;//获取错误的信息 NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];//等到了要刷新界面 NSHTTPURLResponse *httpResponse=(NSHTTPURLResponse*)response; NSString *str=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; NSLog(@"%@",str); } //post方法 - (IBAction)post_btn_touch_up_inside:(id)sender { NSString *strTrainCode=self.m_trainName.text;//获取火车车次代码 NSString *strUserId=@"";//用户id,不需要赋值 NSString *strURL=k4;//请求的URL地址 NSString *strBody=[NSString stringWithFormat:@"TrainCode=%@&UserIDR=%@",strTrainCode,strUserId];//表示后面 NSString *length=[NSString stringWithFormat:@"%d",[strBody length]]; NSMutableURLRequest *request=[[NSMutableURLRequest alloc]init];//客户端向服务端请求的类 [request setURL:[NSURL URLWithString:strURL]];//设置http地址 [request setHTTPMethod:@"POST"];//设置发送方法 [request setTimeoutInterval:10];//设置连接超时,默认240秒 [request setValue:length forHTTPHeaderField:@"Content-Length"];//设置数据长度 [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Contene-Type"];//设置数据格式 [request setHTTPBody:[strBody dataUsingEncoding:NSUTF8StringEncoding]];//设置携带的消息体,准备请求 NSURLResponse *response=nil;//获取服务器的响应返回 NSError *error=nil;//获取错误的信息 NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];//等到了要刷新界面 NSHTTPURLResponse *httpResponse=(NSHTTPURLResponse*)response; NSString *str=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",str); self.m_textView.text=str; }
【文件预览】:
HttpDemo
----HttpDemo.xcodeproj()
--------project.xcworkspace()
--------project.pbxproj(19KB)
--------xcuserdata()
----HttpDemoTests()
--------HttpDemoTests.m(631B)
--------HttpDemoTests-Info.plist(693B)
--------en.lproj()
----.DS_Store(6KB)
----HttpDemo()
--------main.m(329B)
--------HttpDemo-Info.plist(1KB)
--------AppDelegate.h(269B)
--------AppDelegate.m(2KB)
--------Base.lproj()
--------ViewController.h(471B)
--------Images.xcassets()
--------ViewController.m(3KB)
--------en.lproj()
--------HttpDemo-Prefix.pch(344B)

网友评论