iOS POST到Rails JSON跳过错误

时间:2015-12-14 02:18:27

标签: ios ruby-on-rails json

我试图通过我的iOS应用程序向我的localhost服务器发帖。

正确执行此curl命令(从我的iOS应用程序生成的字符串中复制了JSON):

curl -XPOST -H "Content-Type: application/json" -d '{"appuser":{"id":0,"birthday_month":2,"hispanic_origin":"0","marital_status":"1","age":25,"idfa":"A84F55A7-3C6F-4A2E-9379-AB9895863C25","profiled":1,"dob":"2\/16\/1989","quality":1,"zip":"53593","device_type":"x86_64","income":"7","race":"0","children":"36","birthday_year":1989,"education":"7","employment_status":"0","gender":0,"birthday_day":16}}' http://localhost:3000/api/v1/appusers?access_token=6434ba7036431f2c8d12572eab0f2746

在我的iOS应用中,我创建了这样的POST:

NSString *urlStr = [@"http://localhost:3000/api/v1/appusers?access_token=" stringByAppendingString:[NSString stringWithFormat:@"6434ba7036431f2c8d12572eab0f2746"]];

        NSURL *url = [NSURL URLWithString:urlStr];

        NSURLSession *session = [NSURLSession sharedSession];

        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

        request.HTTPBody = [newNewString dataUsingEncoding:NSUTF8StringEncoding];
        request.HTTPMethod = @"POST";
        NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {


        }];
        [postDataTask resume];

但我不断从我的服务器得到400回复说明:

ActionController::ParameterMissing (param is missing or the value is empty: appuser):
  app/controllers/api/v1/appusers_controller.rb:36:in `appuser_params'
  app/controllers/api/v1/appusers_controller.rb:10:in `create'

问题似乎是在发送到我的rails应用程序之前如何转义JSON。在我的服务器中它看起来像这样:

Parameters: {"{\"appuser\":`{\"id\":0,\"birthday_month\":2,\"hispanic_origin\":\"0\",\"marital_status\":\"1\",\"age\":25,\"idfa\":\"A84F55A7-3C6F-4A2E-9379-AB9895863C25\",\"profiled\":1,\"dob\":\"2\\/16\\/1989\",\"quality\":1,\"zip\":\"53593\",\"device_type\":\"x86_64\",\"income\":\"7\",\"race\":\"0\",\"children\":\"36\",\"birthday_year\":1989,\"education\":\"7\",\"employment_status\":\"0\",\"gender\":0,\"birthday_day\":16}}"=>nil, "access_token"=>"6434ba7036431f2c8d12572eab0f2746"}`

但是当我在我的应用程序中注销时,我看到了:

{"appuser":{
  "id" : 0,
  "birthday_month" : 2,
  "hispanic_origin" : "0",
  "marital_status" : "1",
  "age" : 25,
  "idfa" : "A84F55A7-3C6F-4A2E-9379-AB9895863C25",
  "profiled" : 1,
  "dob" : "2\/16\/1989",
  "quality" : 1,
  "zip" : "53593",
  "device_type" : "x86_64",
  "income" : "7",
  "race" : "0",
  "children" : "36",
  "birthday_year" : 1989,
  "education" : "7",
  "employment_status" : "0",
  "gender" : 0,
  "birthday_day" : 16
}}

我还尝试剥离换行符和空格以在我的iOS应用中获取此内容:

{"appuser":{"id":0,"birthday_month":2,"hispanic_origin":"0","marital_status":"1","age":25,"idfa":"A84F55A7-3C6F-4A2E-9379-AB9895863C25","profiled":1,"dob":"2\/16\/1989","quality":1,"zip":"53593","device_type":"x86_64","income":"7","race":"0","children":"36","birthday_year":1989,"education":"7","employment_status":"0","gender":0,"birthday_day":16}}

我的直觉说问题就在于我编码字符串的地方:

request.HTTPBody = [newNewString dataUsingEncoding:NSUTF8StringEncoding];

以下是我创建JSON的方式:

NSMutableDictionary *appuserDictionary = [NSMutableDictionary dictionary];

    NSEntityDescription *entity = [self.appuser entity];
    NSDictionary *attributes = [entity attributesByName];
    for (NSString *attribute in attributes) {
        id attributeValue = [self.appuser valueForKey: attribute];
        if (attributeValue) {
            [appuserDictionary setObject:attributeValue forKey:attribute];
        }
    }

    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:appuserDictionary
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];

    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSString *appuserJsonString = [NSString stringWithFormat:@"{%@:%@}", @"\"appuser\"", jsonString];

        NSString *newString = [[appuserJsonString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:@""];
        NSString *newNewString = [[newString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" "]] componentsJoinedByString:@""];
        NSLog(appuserJsonString);
        NSLog(newNewString);

我是iOS的新手,所以我希望我能错过一些愚蠢的东西。

我的Rails控制器(ApiController基本上只验证access_token):

module Api
  module V1
    class AppusersController < ApiController

      def show
        @appuser = Appuser.find(params[:id])
      end

      def create
        @appuser = Appuser.new(appuser_params)

        respond_to do |format|
          if @appuser.save
            @appuser.update_location
            format.json { render action: 'show', status: :created, location: @appuser }
          else
            format.json { render json: @appuser.errors, status: :unprocessable_entity }
          end
        end
      end

      def update
        @appuser = Appuser.find(params[:id])
        respond_to do |format|
          if @appuser.update(appuser_params)
            format.json { head :no_content }
          else
            format.json { render json: @appuser.errors, status: :unprocessable_entity }
          end
        end
      end

      private
        # Never trust parameters from the scary internet, only allow the white list through.
        def appuser_params
          params.require(:appuser).permit(:age, :income, :city, :zip, :county, :state, :state_code, :country, :gender, :employment_status, :education, :marital_status, :email, :username, :remember_token, :created_at, :updated_at, :coins, :pending_coins, :userGo, :birthday_month, :birthday_day, :birthday_year, :profiled, :quality, :race, :children, :hispanic_origin)
        end
    end
  end
end

1 个答案:

答案 0 :(得分:1)

You have to tell the server that your body is in a JSON format by adding the right request header:

...
request.HTTPBody = [newNewString dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPMethod = @"POST";
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
...