ASIHttprequest NSMutableURLRequest post请求的方便之处

来源:互联网 发布:美食文案 知乎 编辑:程序博客网 时间:2024/05/20 17:09

如果是NSMutableURLRequest   要在请求加入各种字段   其中包括

 NSMutableURLRequest *request =[NSMutableURLRequestrequestWithURL:[NSURLURLWithString:URL]];

    

    //设置发送请求的方式

    [request setHTTPMethod:@"POST"];

    //设置请求体

    [request addValue:@"application/x-www-form-urlencoded"forHTTPHeaderField:@"Content-type"];

    //设置参数

    NSString *body =[NSStringstringWithFormat:@"username=%@&password=%@&email=%@",UsernameTextField.text,PasswordTextField.text,emailTextField.text];

//计算参数的总长度

    int length =[bodylengthOfBytesUsingEncoding:NSUTF8StringEncoding];

    

    //添加字段 Content-Lenth该字段的大小事参数集合的总长度 URL没有关系

    [request addValue:[NSStringstringWithFormat:@"%d",length]forHTTPHeaderField:@"Content-Length"];

    

    NSData  *data =[bodydataUsingEncoding:NSUTF8StringEncoding];

    

    //设置请求体

    [request setHTTPBody:data];    

    //发送请求

    

    _connection =[[NSURLConnectionalloc]initWithRequest:requestdelegate:self];





如果是ASIHTTP的话直接使用

ASIFormDataRequest *request1 =[ASIFormDataRequestrequestWithURL:[NSURLURLWithString:@"http://119.255.38.178:8089/sns/my/login.php"]];

    

    request1.delegate=self;

    //Key 是来自开发文档

    [request1 addPostValue:@"test"forKey:@"username"];

    [request1 addPostValue:@"123456"forKey:@"password"];

    

    [request1 startAsynchronous];


0 0
原创粉丝点击