【问题标题】:iOS JSON auth token request says missing parameteriOS JSON 身份验证令牌请求说缺少参数
【发布时间】:2023-03-20 15:21:01
【问题描述】:

我一直在寻找,似乎无法弄清楚这一点。 我看到的所有 JSON 示例都没有在 url 中有方法名称,所以我认为这可能是一个问题。 这是我的代码:

NSString *username = @"xxxx";
NSString *password = @"xxxx";
NSString *loginURL = @"http://www.xxxxxx.com/services/api/rest/json?method=xxxxxx.auth.gettoken";

NSURL *url = [NSURL URLWithString:loginURL];

NSString *JSONString = [NSString stringWithFormat:@"{\"username\":\"%@\",\"password\":\"%@\"}", username, password];

NSData *JSONBody = [JSONString dataUsingEncoding:NSUTF8StringEncoding];

NSMutableURLRequest *loginRequest = [[NSMutableURLRequest alloc] initWithURL:url];
loginRequest.HTTPMethod = @"POST";
loginRequest.HTTPBody = JSONBody;

NSOperationQueue *queue = [NSOperationQueue new];

[NSURLConnection sendAsynchronousRequest:loginRequest 
                                   queue:queue 
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){

                           // Manage the response here.
                           NSString *txt = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
                           NSLog(@"%@", txt);
                       }];

我正在使用 SquidMan 窥探请求,我注意到访问日志列出: www.xxxxx.com/services/api/rest/json? - 直接的/..... 方法名称不存在,这是我第一次使用 SquidMan,但我认为它会存在。

我得到的信息是参数用户名丢失。

提前谢谢你。

【问题讨论】:

    标签: objective-c ios json


    【解决方案1】:

    我发现了问题,我没有编写 web 服务,显然以 JSON 格式发送数据是错误的。 如果我以“&param=value&param2=value2”的格式发布数据,它就可以工作。

        NSString *JSONString = [NSString stringWithFormat:@"&username=%@&password=%@",
                          [username stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                          [password stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSData *JSONBody = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest *loginRequest = [[NSMutableURLRequest alloc] initWithURL:url];
    loginRequest.HTTPMethod = @"POST";
    loginRequest.HTTPBody = JSONBody;
    

    【讨论】:

      【解决方案2】:

      这可能是因为您没有为您的请求指定Content-Type,所以服务器不知道如何解释数据。分配 loginRequest 后尝试将此行添加到您的代码中:

      [loginRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
      

      希望对您有所帮助。

      【讨论】:

      • 感谢您的建议,但仍然无法正常工作。相同的缺失参数返回值。我会将您的建议留在我的代码中。
      猜你喜欢
      • 2017-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-21
      • 2016-09-04
      • 2017-12-20
      • 2018-08-03
      • 1970-01-01
      相关资源
      最近更新 更多