POST
?
?
?
?
?
/*(http)get請求和post請求的區別:
?*1、post請求 請求地址和參數分離,比get更加安全
?*2、get請求只能獲取服務器的數據不能上傳文件,而post兩者都可以
?*3、get請求在瀏覽器中字符串長度最大限制為1024,post 沒有限制
?*4、post 上傳文件 文件大小不能超過4G
?*/
?
?
?
四種body參數的組織方式,對應四種contentType:? (一般都是用默認的第一種)
1、application/x-www-form-urlencoded ? 參數拼接形態:a=@"haha"&b=@"hehe"&c=@"houhou"
2、multipart/form-data ? 參數為文本或者二進制
3、application/json? 參數為json格式
4、text/xml 參數為xml格式
?
?
?
?
【NSURLConnection POST用法】
?
?
NSURL *url = [NSURL URLWithString:urlStr];
? ? //post請求用NSMutableURLRequest,可變request的請求頭
? ? NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
?
? ? //設置數據的請求方式(GET/POST)為post請求*****
? ? [request setHTTPMethod:@"POST"];
?
//設置請求參數的編碼方式(請求頭的一部分),可以缺省不寫
? ? [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
?
//將參數的字符串轉換成NSData
NSData *data = [@"username=111&email=33333&password=22222" dataUsingEncoding:NSUTF8StringEncoding];
?
//設置參數的長度(請求頭的一部分)可以不寫
[request setValue:[NSString stringWithFormat:@"%d",[data length]] forHTTPHeaderField:@"Content-Length"];
?
//將參數的data作為請求體*****
? ? [request setHTTPBody:data];
?
//<NSURLConnectionDataDelegate>
[NSURLConnection connectionWithRequest:request delegate:self];
?
?
?
?
?
?
【ASIFormDataRequest POST用法】
?
?
使用系統相冊
?
1,找開系統相冊
UIImagePickerController *ipc = [[UIImagePickerController alloc]init];//照片選擇器
? ? ipc.delegate = self;//<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
? ? [self presentViewController:ipc animated:YES completion:nil];
?
?
//選擇照片后觸發用post上傳
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
? ? NSUserDefaults* ud = [NSUserDefaults standardUserDefaults];
? ? NSString* urlStr = @"http://192.168.88.8/sns/my/upload_headimage.php";
? ? NSString* m_auth = [ud objectForKey:@"m_auth"];
?
//獲取點擊的圖片
? ? UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
//將圖片轉化為二進制數據
? ? NSData* headData = UIImagePNGRepresentation(image);
?? ?
//ASI中,進行post請求和文件上傳用ASIFormDataRequest
//#import "ASIFormDataRequest.h"
? ? ASIFormDataRequest* request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlStr]];
?
//可以缺省不寫
? [request setRequestMethod:@"POST"];
?
//普通的參數(key=value),如果有多個參數需要多次添加
? ? [request setPostValue:m_auth forKey:@"m_auth"];
//[request addPostValue:m_auth forKey:@"m_auth"];
?
//需要上傳文件(轉成的二進制數據) fileName:圖片的名稱,ContentType:上傳的文件類型,key為文件對應的參數名稱
? ? [request setData:headData withFileName:@"tmp.png" andContentType:@"image/png" forKey:@"headimage"];
//[request addData:headData withFileName:@"tmp.png" andContentType:@"image/png" forKey:@"headimage"];
?
//<ASIHTTPRequestDelegate>
? ? request.delegate = self;
? ? [request startAsynchronous];
?? ?
? ? [picker dismissViewControllerAnimated:YES completion:nil];
}
?
//點擊照片選擇器右側按鈕執行
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
? ? [picker dismissViewControllerAnimated:YES completion:nil];
}?
?????
?
?
?
#import "LoginViewController.h"
#import "Regist.h"
#import "ASIFormDataRequest.h"
#import "HomeViewController.h"
@interface LoginViewController ()<RegistViewControllerDelegate,ASIHTTPRequestDelegate>
@property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (weak, nonatomic) IBOutlet UITextField *passTF;
?
@end
?
@implementation LoginViewController
?
- (void)viewDidLoad {
? ? [super viewDidLoad];
? ? // Do any additional setup after loading the view from its nib.
? ? self.navigationItem.title=@"Login";
?? ?
?? ?
?? ?
}
- (IBAction)btnClick:(UIButton *)sender
{
? ? [self.view endEditing:YES];
? ? if (sender.tag==1) {
?? ? ? ?
? ? ? ? //登錄接口
? ? ? ? NSString *urlStr=@"http://10.0.8.8/sns/my/login.php";
?? ? ? ?
? ? ? ? //用asi窗前post請求需要用這個類
? ? ? ? ASIFormDataRequest *request=[[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:urlStr]];
?? ? ? ?
? ? ? ? //設置請求方式(asi使用post可以省略)
? ? ? ? [request setRequestMethod:@"POST"];
?? ? ? ?
? ? ? ? //添加一個參數
? ? ? ? [request setPostValue:_nameTF.text forKey:@"username"];
?? ? ? ?
? ? ? ? //又添加一個參數
? ? ? ? [request setPostValue:_passTF.text forKey:@"password"];
?? ? ? ?
? ? ? ? request.delegate=self;
?? ? ? ?
? ? ? ? //加載請求
? ? ? ? [request startAsynchronous];
?? ? ? ?
? ? } else {
? ? ? ? Regist *rvc=[[Regist alloc]init];
? ? ? ? rvc.delegate=self;
? ? ? ? [self.navigationController pushViewController:rvc animated:YES];
? ? }
?? ?
}
?
-(void)requestFinished:(ASIHTTPRequest *)request
{
? ? NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:request.responseData options:0 error:nil];
?? ?
? ? if ([[dic objectForKey:@"code"]isEqualToString:@"login_success"]) {
? ? ? ? //用戶的身份標記
? ? ? ? NSString *mauth=[dic objectForKey:@"m_auth"];
?? ? ? ?
? ? ? ? //將身份標記用mauth這個key存到ud里
? ? ? ? NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];
? ? ? ? [ud setObject:mauth forKey:@"mauth"];
? ? ? ? [ud synchronize];
?? ? ? ?
? ? ? ? HomeViewController *hvc=[[HomeViewController alloc]init];
? ? ? ? [self.navigationController pushViewController:hvc animated:YES];
?? ? ? ?
?? ? ? ?
? ? ? ? return;
? ? }
?? ?
? ? UIAlertView *av=[[UIAlertView alloc]initWithTitle:[dic objectForKey:@"code"] message:[dic objectForKey:@"message"] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
? ? [av show];
}
?
-(void)requestFailed:(ASIHTTPRequest *)request
{
? ? NSLog(@"%s",__func__);
}
?
-(void)registSuccessWithName:(NSString *)name pass:(NSString *)pass
{
? ? _nameTF.text=name;
? ? _passTF.text=pass;
}
?
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
? ? [self.view endEditing:YES];
}
?
?
- (void)didReceiveMemoryWarning {
? ? [super didReceiveMemoryWarning];
? ? // Dispose of any resources that can be recreated.
}
?
/*
#pragma mark - Navigation
?
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
? ? // Get the new view controller using [segue destinationViewController].
? ? // Pass the selected object to the new view controller.
}
*/
?
@end
?
?
?
?
?
?
?
?
?
?
?
?
?
#import <UIKit/UIKit.h>
?
@protocol RegistViewControllerDelegate <NSObject>
?
-(void)registSuccessWithName:(NSString *)name pass:(NSString *)pass;
?
@end
?
@interface Regist : UIViewController
@property(nonatomic,assign)id<RegistViewControllerDelegate>delegate;
@end
?
?
?
?
?
?
?
?
?
?
?
?
#import "Regist.h"
?
@interface Regist ()<NSURLConnectionDataDelegate,UIAlertViewDelegate>
{
? ? NSMutableData *_downloadData;
}
@property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (weak, nonatomic) IBOutlet UITextField *passTF;
@property (weak, nonatomic) IBOutlet UITextField *mailTF;
?
@end
?
@implementation Regist
?
- (void)viewDidLoad {
? ? [super viewDidLoad];
? ? // Do any additional setup after loading the view from its nib.
? ? self.navigationItem.title=@"Reglist";
? ? _downloadData=[[NSMutableData alloc]init];
?? ?
?? ?
?? ?
}
- (IBAction)saveClick:(UIButton *)sender {
? ? [self.view endEditing:YES];
?
? ? if (!_nameTF.text.length || !_passTF.text.length || !_mailTF.text.length) {
? ? ? ? UIAlertView *av =[[UIAlertView alloc]initWithTitle:@"Massage" message:@"Please Write things" delegate:nil cancelButtonTitle:@"Yes" otherButtonTitles: nil];
? ? ? ? [av show];
? ? ? ? return;
? ? }
?? ?
? ? //所有參數拼接成的字符串,作為請求體
? ? NSString *bodyStr=[NSString stringWithFormat:@"username=%@&password=%@&email=%@",_nameTF.text,_passTF.text,_mailTF.text];
?? ?
? ? //接口(網址)部分,作為請求頭
? ? NSString *urlStr=@"http://10.0.8.8/sns/my/register.php";
?? ?
? ? NSURL *url=[NSURL URLWithString:urlStr];
?? ?
? ? //使用post聯網需要可變的request
? ? NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:15];
?? ?
? ? //設置請求方式為POST(POST/GET)
? ? [request setHTTPMethod:@"POST"];
?? ?
? ? //設置請求體(需要把參數的字符串轉化成NSData)
? ? [request setHTTPBody:[bodyStr dataUsingEncoding:NSUTF8StringEncoding]];
?? ?
? ? //加載請求
? ? [NSURLConnection connectionWithRequest:request delegate:self];
?? ?
? ? [UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
?? ?
}
?
#pragma mark - NSRULConnection
?
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
? ? _downloadData.length=0;
}
?
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
? ? [_downloadData appendData:data];
}
?
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
? ? [UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
?? ?
? ? NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:_downloadData options:0 error:nil];
?? ?
? ? UIAlertView *av=[[UIAlertView alloc]initWithTitle:[dic objectForKey:@"code"] message:[dic objectForKey:@"message"] delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
? ? [av show];
? ? if ([[dic objectForKey:@"code"] isEqualToString:@"registered"]) {
? ? ? ? av.tag = 1;
? ? }
? ? [av show];
}
?
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
? ? if (alertView.tag == 1) {
? ? ? ? [self.navigationController popToRootViewControllerAnimated:YES];
? ? ? ? [self.delegate registSuccessWithName:_nameTF.text pass:_passTF.text];
? ? } else {
?? ? ? ?
? ? }
}
?
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
? ? [UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
? ? NSLog(@"%s",__func__);
}
?
?
?
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
? ? [self.view endEditing:YES];
}
?
- (void)didReceiveMemoryWarning {
? ? [super didReceiveMemoryWarning];
? ? // Dispose of any resources that can be recreated.
}
?
/*
#pragma mark - Navigation
?
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
? ? // Get the new view controller using [segue destinationViewController].
? ? // Pass the selected object to the new view controller.
}
*/
?
@end
?
?
?
?
?
?
?
?
?
?
?
?
#import "HomeViewController.h"
#import "ASIFormDataRequest.h"
@interface HomeViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,ASIHTTPRequestDelegate>
{
? ? //圖片選擇控制器
? ? UIImagePickerController *_ipc;
}
@property (weak, nonatomic) IBOutlet UIImageView *headView;
?
@end
?
@implementation HomeViewController
?
- (void)viewDidLoad {
? ? [super viewDidLoad];
? ? // Do any additional setup after loading the view from its nib.
}
- (IBAction)btnClick:(UIButton *)sender {
? ? if (!_ipc) {
? ? ? ? _ipc=[[UIImagePickerController alloc]init];
? ? }
? ? _ipc.delegate=self;
?? ?
? ? [self presentViewController:_ipc animated:YES completion:nil];
}
?
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
? ? NSLog(@"%@",info);
?? ?
? ? //將點擊的圖片顯示到headView上
? ? _headView.image=[info objectForKey:UIImagePickerControllerOriginalImage];
?? ?
? ? NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];
? ? NSString *mauth=[ud objectForKey:@"mauth"];
?? ?
? ? //創建一個asi的post請求
? ? ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"http://10.0.8.8/sns/my/upload_headimage.php"]];
?? ?
? ? //告訴服務器,要為哪個用戶上傳頭像
? ? [request setPostValue:mauth forKey:@"m_auth"];
?? ?
? ? //將圖片轉成NSData
? ? NSData *imageData=UIImagePNGRepresentation(_headView.image);
?? ?
? ? //將圖片轉成NSData,第二個參數圖片名,供后臺參考,第三個文件類型,圖片就用image/png,最后一個參數是后臺規定的參數名
? ? [request setData:imageData withFileName:@"2.png" andContentType:@"image/png" forKey:@"headimage"];
?? ?
? ? request.delegate=self;
? ? [request startAsynchronous];
?? ?
? ? //讓對應的圖片選擇器退出
? ? [picker dismissViewControllerAnimated:YES completion:nil];
}
?
-(void)requestFinished:(ASIHTTPRequest *)request
{
? ? NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:request.responseData options:0 error:nil];
?? ?
? ? UIAlertView *av=[[UIAlertView alloc]initWithTitle:[dic objectForKey:@"code"] message:[dic objectForKey:@"message"] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
? ? [av show];
}
?
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
? ? [self.view endEditing:YES];
}
?
- (void)didReceiveMemoryWarning {
? ? [super didReceiveMemoryWarning];
? ? // Dispose of any resources that can be recreated.
}
?
/*
#pragma mark - Navigation
?
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
? ? // Get the new view controller using [segue destinationViewController].
? ? // Pass the selected object to the new view controller.
}
*/
?
@end
?
轉載于:https://www.cnblogs.com/-yun/p/4390945.html
總結
- 上一篇: 相关资源
- 下一篇: ibatis解决sql注入问题