Sending an HTTP POST request on iOS

因为项目需要,模拟form提交post请求。其实,早就使用了这个方法,但是,一直没有数据反馈回来,直到看到这篇,此处需要主要的是编码方式,和文件头。


The following code describes a simple example using POST method.(How one can pass data by POSTmethod)

You can use the following code snippet, as described in this article:

Here, I describe how one can use of POST method.

1. Set post string with actual username and password.

NSString *post = [NSString stringWithFormat:@"Username=%@&Password=%@",@"username",@"password"]; 

2. Encode the post string using NSASCIIStringEncoding and also the post string you need to send in NSData format.

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 

You need to send the actual length of your data. Calculate the length of the post string.

NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]]; 

3. Create a Urlrequest with all the properties like HTTP method, http header field with length of the post string. Create URLRequest object and initialize it.

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; 

Set the Url for which your going to send the data to that request.

[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.abcde.com/xyz/login.aspx"]]]; 

Now, set HTTP method (POST or GET). Write this lines as it is in your code.

[request setHTTPMethod:@"POST"]; 

Set HTTP header field with length of the post data.

[request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 

Also set the Encoded value for HTTP header Field.

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

Set the HTTPBody of the urlrequest with postData.

[request setHTTPBody:postData];

4. Now, create URLConnection object. Initialize it with the URLRequest.

NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self]; 

It returns the initialized url connection and begins to load the data for the url request. You can check that whether you URL connection is done properly or not using just if/else statement as below.

if(conn) {
    NSLog(@"Connection Successful");
} else {
    NSLog(@"Connection could not be made");
}

5. To receive the data from the HTTP request , you can use the delegate methods provided by the URLConnection Class Reference. Delegate methods are as below.

// This method is used to receive the data which we get using post method.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data

// This method receives the error report in case of connection is not made to server. 
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 

// This method is used to process the data after connection has made successfully.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection

Also Refer This and This documentation for POST method.

And here is best example with source code of HTTPPost Method.


再添加一个GET方法

    NSString *urlString = [NSString stringWithFormat:@"https://www.xxxx.com",one,two];
    // 设置编码方式
    NSString *urlEncode = [urlString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
    NSURL *url = [NSURL URLWithString:urlEncode];
    
    // 创建NSURLReauest对象 设置缓存机制 和 超时时长
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:50];
    
    // 请求方式
    [request setHTTPMethod:@"GET"];
    // 添加请求头
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    //    以制定的URL delegate 创建连接 发送请求
    NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
    if (conn==nil) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"网络连接失败" message:@"失去网络连接" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"我知道了", nil];
        [alertView show];
    }





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值