//
// ViewController.m
// 2、GET\POST
//
// Created by yongma00 on 15/12/10.
// Copyright © 2015年 yongma. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
- (IBAction)getBtnPressed:(id)sender;
- (IBAction)postBtnPressed:(id)sender;
@property (weak, nonatomic) IBOutlet UILabel *label;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
#pragma mark NSURL
NSURL *url=[NSURL URLWithString:@"http://tieba.baidu.com/f?kw=%C0%EE%D2%E3"];
NSLog(@"协议:%@",url.scheme);
NSLog(@"主机:%@",url.host);
NSLog(@"路径:%@",url.path);
NSLog(@"端口:%@",url.port);
NSLog(@"请求参数:%@",url.query);
}
-(void)getRequest{
//1、生成一个请求的url
NSString *str=@"http://192.168.0.100:8080/MJServer/login?username=123&pwd=123&method=get&type=JSON";
NSURL *url=[NSURL URLWithString:str];
//2、根据url生成一个请求
NSURLRequest *request=[NSURLRequest requestWithURL:url];
//3、建立网络连接
NSHTTPURLResponse *response=nil;
NSError *error;
NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//4、打印所有的请求头和响应头
// NSLog(@"请求头:%@",request.allHTTPHeaderFields);
NSLog(@"响应头:%@",response.allHeaderFields);
//5、把数据转换成字符串
NSString *msg=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
self.label.text=msg;
}
-(void)postRequest{
NSString *str=@"http://192.168.0.100:8080/MJServer/login";
NSURL *url=[NSURL URLWithString:str];
NSData *postData=[@"username=123&pwd=123" dataUsingEncoding:NSUTF8StringEncoding];
//创建一个可变的请求对象
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
//设置请求方法
[request setHTTPMethod:@"POST"];
//设置请求参数
[request setHTTPBody:postData];
//设置请求超时的时间
[request setTimeoutInterval:60];
// NSLog(@"post请求头:%@",request.allHTTPHeaderFields);
//创建response
NSHTTPURLResponse *response=nil;
NSError *error;
//建立网络连接
NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *msg=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
self.label.text=msg;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)getBtnPressed:(id)sender {
[self getRequest];
}
- (IBAction)postBtnPressed:(id)sender {
[self postRequest];
}
@end