ios使用POST参数发送POST请求

时间:2014-01-23 10:48:55

标签: ios post parameters request

我已经编写了一个iOS应用程序,它通过POST成功将字符串上传到服务器。

bodyString = [NSString stringWithFormat:@"text1=%@&submit1=+Absenden+", contentString];

request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://www.xxx /xxx/get.jsp"]];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[bodyString dataUsingEncoding:NSUTF8StringEncoding]];

self.connection = [NSURLConnection connectionWithRequest:request delegate:self];

我需要更改服务器,所以我使用相同的代码,但它不起作用,虽然我得到200状态代码。负责新服务器的人说它不起作用,因为我发送的是POST,但我没有将字符串作为POST参数发送。

不幸的是她不懂iOS所以无法解释我该怎么做。我已经四处寻找,但我找不到任何东西,但仍然不明白:发送POST是什么意思,同时发送一个字符串作为POST参数?

任何帮助都会非常友好。

2 个答案:

答案 0 :(得分:4)

借助NSURLConnection委托方法处理结果数据

  NSString *post = [NSString stringWithFormat:@"postBody=%@",@"Raja"];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[post length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://localhost/promos/index.php"]];


    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];

    NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];

    if( theConnection ){
        // indicator.hidden = NO;
        mutableData = [[NSMutableData alloc]init];
    }

您的PHP代码

<?php
    $result = $_POST['postBody'];


    echo $result;
?>

答案 1 :(得分:1)

我总是将AFNetworking用于任何网络任务。它不仅可以加快您的开发速度,还可以处理许多艰苦的网络任务。它是开发人员广泛使用的框架。

AFNetworking

这就是你发送帖子请求的方式:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
[manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

您可以非常轻松地捕获各自块中的响应或错误。