我正在使用 Android 应用程序提交到 Rails 应用程序,该应用程序具有托管在 Heroku 上的 Mongo 后端。我可以使用在线表单将新项目提交到 mongo 数据库中,但是当我尝试从 Android 应用程序提交 JSON 时,我得到:
{"error":"无法处理的实体","status":"422"}
我认为这可能与我提交时 JSON 的顺序有关,因为它似乎按照我意识到根据 a past SO question 是正常的顺序混淆了。 。但是,这个问题的解决方案对我来说不起作用。
以下是我的 Android 应用程序中 JSONObject 的构造:
JSONObject jsonObject = new JSONObject();
jsonObject.put("ph", 2);
jsonObject.put("chlorine", 2.0);
jsonObject.put("magnified_Link", url);//URLEncoder.encode(encodedImage, "UTF-8"));
jsonObject.put("taste", "yucky");
jsonObject.put("odor", "smelly");
jsonObject.put("temperature", "77.0");
jsonObject.put("mercury", 234);
jsonObject.put("hardness", 9.0);
jsonObject.put("lat", latitude);
jsonObject.put("long", longitude);
String json = jsonObject.toString(); // Output to string
Log.d(TAG, json);
StringEntity se = new StringEntity(json);
// put json string into server
httpPost.setEntity(se);
//httpPost.setHeader("Authorization", "Client-ID " +API_KEY);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
这是当我在提交之前记录它时 JSON 在我的 Android 应用程序中的显示方式:
{"chlorine":2,"odor":"smelly","magnified_Link":"http:\/\/i.imgur.com\/JnbuUwy.jpg","long":0,"hardness":9,"ph":2,"taste":"yucky","lat":0,"mercury":234,"temperature":"77.0"}
这是我的 JSON 页面在我的 Rails 应用程序上的样子,通过在线 Rails 应用程序成功提交到其中:
[{"id":{"$oid":"558766f26633380003000000"},"ph":1.0,"chlorine":2.0,"magnified_Link":"3","taste":"4","odor":"5","temperature":6.0,"mercury":7.0,"hardness":8.0,"lat":40.7127,"long":-74.0059,"url":"https://distributed-health.herokuapp.com/distributed_healths/558766f26633380003000000.json"}]
最后,这是我的 Rails 应用程序中“DistributedHealth”(我的对象)的模型:
class DistributedHealth
include Mongoid::Document
field :ph, type: Float
field :chlorine, type: Float
field :magnified_Link, type: String
field :taste, type: String
field :odor, type: String
field :temperature, type: Float
field :mercury, type: Float
field :hardness, type: Float
field :lat, type: Float
field :long, type: Float
end
我可以添加任何其他相关代码,并在继续尝试解决此问题时对这篇文章进行编辑。
谢谢,
克莱顿。
编辑:我收到来自 Heroku 服务器的错误消息
2015-06-23T21:29:34.382730+00:00 heroku[router]: at=info method=POST path="/distributed_healths.json" host=distributed-health.herokuapp.com request_id=2dcde4a4-3dcc-4381-98ba-6ca399400a6d fwd="128.54.58.245" dyno=web.1 connect=3ms service=14ms status=422 bytes=328
最佳答案
问题最终是 Rails 方面的问题,与提交的 JSON 的顺序无关。我发现使用 class DistributedHealthsController < ApplicationController
之后的行需要 CSRF token 在我的 Controller 中:
skip_before_action :verify_authenticity_token
不建议这样做,因为这是一种解决安全问题的方法,但如果您想排除某些方法 this post将向您展示如何操作。
有关该主题的更多讨论可以找到 here可以找到有关该主题的一些文档 here .
尽管我现在可以对我的 Rails 应用程序执行 POST,但我的 Android Studio 日志中仍然收到错误 500,如下所示:
{"error":"Internal Server Error","status":"500"}
它现在似乎并没有妨碍功能,所以我不会因此而失眠。
关于android - 提交到 Rails 时 JSON 导致实体无法处理(错误 422),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31011293/