//设置二进制数据

ios开发-get和post,ios开发-getpost

直接上代码:

示例:(在storyboard中拖两个控件textField、一个UIButton,连线(userNameText、password、login))

@interface ViewController()

@property(nonatomic,weak)IBOutlet UITextField *userNameText;

@property(nonatomic,weak)IBOutlet UITextField *passWord;

@end

 

-(IBAction)login

{

  [self postLoginWithUserName:self.userNameText.text 
password:self.passWord.text];

}

post登陆

-(void)postLoginWithUserName:(NSString *)userName  password:(NSString
*)password
{

  //1.url

  NSURL *url = [NSURL URLWithString:@”];

  //2.request

  NSMutableNSURLRequest *request = [NSMutableNSURLRequest
requestWithURL:url];

  //对于post请求的数据题要和request一起提交

  request.HTTPMethod = @”POST”;

 

  //准备数据题

  NSString *bodyString = [NSString
*stringWithFormat:@”username=%@&password=%@”,username,password];

  //设置二进制数据

  request.HTTPBody = [bodyString
dataUsingEncoding:NSUTF8StringEncoding];

  

 

  //3.发送网络连接,获取二进制数据

  [NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLReponse
*response,NSData *data,NSError *connectionError)]; 

 NSString *result = [NSString alloc]initWithData:data
encoding:NSUTF8Encoding];

}

 

 

 

 

get登陆

-(void)getLoginWithUserName:(NSString *)userName  password:(NSString
*)password

{

  //1.url

  NSString *urlString = [NSString
stringWithFormat:@” = %@&password =
%@”,userName,password];

  //百分号转义

  urlString = [urlString
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

  NSURL *url = [NSURL URLWithString:urlString];

  //2.request

  NSURLRequest *request = [NSURLRequest requestWithURL:url];

  //3.发送网络连接,获取二进制数据

  [NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLReponse
*response,NSData *data,NSError *connectionError)];

  NSString *result = [NSString alloc]initWithData:data
encoding:NSUTF8Encoding];

}

 

小结:

1.

get:

= %@&password = %@

=
参数数值&(继续接参数)变量名 = 数值

post

2.request

get:什么都不需要处理,因为参数已经在URL中指定了

post:指定访问方法

  HTTPMethod = @”post”;

  

  指定二进制数据

  HTTPBody = 参数字符串的二进制数据

 

3.NSURLConnection 异步

get和post一样

 

在实际网络开发中,真正会发生变化的地方就在请求

 

iOS开发,怎设置post异步超时?

ios异步请求的话可以使用系统本身的,也可以使用第三方的,系统本身的需要设置一些东西,比较繁琐,建议是用第三方类库ASI
给你一个上传图片的示例: NSURL *url = [NSURL URLWithString:[NSString
stringWithFormat:@”91iu.com/cutpic/shearPic”]];
NSData * data = nil;
data = UIImagePNGRepresentation(image);
if (!data) {
data = UIImageJPEGRepresentation(image, 1);
}

ASIFormDataRequest *request = [ASIFormDataRequest
requestWithURL:url];
request.requestMethod = @”POST”;
request.timeOutSeconds = 20;
request.delegate = self;
[request setData:data withFileName:@”11.jpg”
andContentType:@”image/jpg” forKey:@”pic”];
[request startSynchronous];
 

如果在iOS项目中POST?

这个得看你post的是什么东西,你服务器接收的是什么东西,如果是简单的字符串,直接提交就ok了,不需要设置头什么的。如果是其他的文件的东西你可能要模拟表单提交,这个得看你们服务器是否能支持了。
 

直接上代码:
示例:(在storyboard中拖两个控件textField、一个UIButton,连线(userNameText、password、login))
@…

相关文章