// ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
// ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self post];
}
-(void)get
{
//0.确定请求路径字符串
//把字符串转换为URL的时候内部不能包含中文
//http://120.25.226.186:32812/login2?username=%E5%B0%8F%E7%A0%81%E5%93%A5&pwd=520it&type=JSON
//NSString *urlStr = @"http://120.25.226.186:32812/login2?username=%E5%B0%8F%E7%A0%81%E5%93%A5&pwd=520it&type=JSON";
NSString *urlStr = @"http://120.25.226.186:32812/login2?username=故宫&pwd=123&type=JSON";
NSLog(@"转码前 urlstr:%@",urlStr);
//对中文进行转码
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"转码后 urlstr:%@",urlStr);
//1.确定URL
NSURL *url = [NSURL URLWithString:urlStr];
//2.创建可变的请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//3.发送GET请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//4.解析数据
NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
NSLog(@"%@",connectionError);
}];
}
-(void)post
{
//0.确定请求路径字符串
NSString *urlStr = @"http://120.25.226.186:32812/login2";
//1.确定URL
NSURL *url = [NSURL URLWithString:urlStr];
//2.创建可变的请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
request.HTTPBody = [@"username=故宫&pwd=123&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];
//3.发送GET请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//4.解析数据
NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
NSLog(@"%@",connectionError);
}];
}
网友评论