简体   繁体   English

IOS到基于REST的MVC Api服务-[获取]有效,但参数无法通过[发布]到达服务器

[英]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. 我可以在我的api控制器上达到Get函数。 I can reach the Post method, but my parameter (macAddress) is null. 我可以到达Post方法,但是我的参数(macAddress)为空。 I've tried many variations of this code in xcode: 我在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]. 看起来您的* postString没有[NSString stringWithFormat方法]。 I use the following code with my own restful API. 我将以下代码与自己的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'。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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