使用AFNetworking的iOS客户端正在向服务器发送带有“%”字符的JSON参数

时间:2013-02-18 23:24:13

标签: ruby-on-rails json urlencode afnetworking params

我的iOS设备正在向我的Rails服务器发送JSON参数,当我将内容输出到控制台时。我看到奇怪的字符在params散列中。然后,服务器方法无法使用这些参数创建对象。并且数据库中没有保存任何内容。 我该如何解决? 感谢

从iOS设备发送JSON的代码:

    //Create a Dictionary of Parameters which will be convertedto JSON object
     NSMutableDictionary *mutableParameters = [NSMutableDictionary dictionary];

    [mutableParameters setObject:_entryID forKey:@"id"];
    [mutableParameters setObject:fnameExt forKey:@"image_file_name"];
    [mutableParameters setObject:_lat forKey:@"lat"];
    [mutableParameters setObject:_longitude forKey:@"lng"];
    [mutableParameters setObject:_description forKey:@"description"];

     NSMutableDictionary *photoDict = [NSMutableDictionary dictionaryWithObjects:[NSArray arrayWithObject:mutableParameters]
      forKeys:[NSArray arrayWithObject:@"photo"]];

     //Create a Request Object
      NSMutableURLRequest *mutableURLRequest = [[appAPIClient sharedClient]
                                          multipartFormRequestWithMethod:@"POST"
                                          path:@"/photos"
                                          parameters:photoDict

      constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
                                          { .....}

我的rails服务器

 # POST /photos
 # POST /photos.json
 def create
    @photo = Photo.new(params[:photo])
    puts "Photo ="
    puts "Server received Photo with attributes= #{@photo.inspect}"
    @photo.save
 end

服务器上的控制台输出

 15:11:19 web.1  | Photo =
 15:11:20 web.1  | Server received Photo with attributes= #<Photo id: nil, lat: nil, 
  lng: nil, created_at: nil, updated_at: nil, image_file_name: "someFile.jpg", 
  image_content_type: "image/jpeg", image_file_size: 0, image_updated_at: "2013-02-
 18 23:11:17">

  15:11:20 web.1  | Started POST "/photos" for 127.0.0.1 at 2013-02-18 15:11:17 -0800
  15:11:20 web.1  | Processing by PhotosController#create as JSON
  15:11:20 web.1  |   Parameters: {"photo%5BentryID%5D"=>"1", 
  "photo%5Blng%5D"=>"-122.406417", "photo%5Blat%5D"=>"37.785834", 
  "photo%5Bimage_file_name%5D"=>"someFile.jpg", 
  "photo%5Bdescription%5D"=>"Description", "photo"=>{"image"=>#
  <ActionDispatch::Http::UploadedFile:0x007fa314c07768 
  @original_filename="someFile.jpg", @content_type="image/jpeg", @headers="Content-
  Disposition: form-data; name=\"photo[image]\"; 
 filename=\"someFile.jpg\"\r\nContent-Type: image/jpeg\r\n", @tempfile=#
  <File:/var/folders/dh/1k2rdp_51yd2k43xzkc2pmdh0000gn/T/RackMultipart20130218-2872-
  13gqqo5>>}}

1 个答案:

答案 0 :(得分:1)

iOS客户端将参数名称编码为URL。例如“photo%5BentryID%5D”是“photo [entryID]”你需要对它们进行编码,虽然这个过程应该在服务器端自动完成,你应该检查你的iOS客户端是不是对它们进行双重编码。 / p>