简体   繁体   中英

IOS to REST-ful MVC Api Service - [Get] works, but parameters don't reach server with [Post]

I think the title explains it. I can reach the Get functions on my api controllers just fine. I can reach the Post method, but my parameter (macAddress) is null. I've tried many variations of this code in xcode:

        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",baseURL,controller]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
NSString *postString = @"macAddress=testestest";
NSData *myRequestData = [ NSData dataWithBytes: [ postString UTF8String ] length: [ postString length ] ];
[request setHTTPBody:myRequestData];

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

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

and the controller:

    public String Post([FromBody]string macAddress)
    {
        //......
    }

(I'm aware that I'm using synchronous requests and nil response/errors, just trying to figure out this aspect)

Thanks for the help.

It looks like you have your *postString without the [NSString stringWithFormat method]. I use the following code with my own restful API.

NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"rsdevicetoken"];

NSString *postString = [NSString stringWithFormat:@"token=%@&active=%@&draw=%@&result=%@&message=%@",deviceToken,allNotify, draw, results, message];
NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://www.someurl.com/updateSubscriptions"]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];

NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(@"%@", data);

Hopefully this will help you.

这是一个疯狂的猜测,但是如果您的macAddress post参数具有以下格式: 01:23:45:67:89:ab ,则需要将':'进行url编码为'%3A'。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM