【发布时间】:2014-01-30 04:49:05
【问题描述】:
我有一个 Android 应用程序发布到我的 sinatra 服务。早些时候,我无法读取我的 sinatra 服务的参数。但是,在我将内容类型设置为“x-www-form-urlencoded”之后。我能够看到参数,但不是我想要的。我在我的 sinatra 服务中得到了一些作为请求参数的东西。
{"{\"user\":{\"gender\":\"female\"},\"session_id\":\"7a13fd20-9ad9-45c2-b308-
8f390b4747f8\"}"=> nil, "splat"=>["update_profile.json"], "captures"=>["update_profile.json"]}
这就是我从我的应用发出请求的方式。
StringEntity se;
se = new StringEntity(getJsonObjectfromNameValueList(params.get_params(), "user");
se.setContentType("application/x-www-form-urlencoded");
postRequest.setEntity(se);
private JSONObject getJsonObjectfromNameValueList(ArrayList<NameValuePair> _params, String RootName) {
JSONObject rootjsonObject = new JSONObject();
JSONObject jsonObject = new JSONObject();
if (_params != null) {
if (!_params.isEmpty()) {
for (NameValuePair p : _params) {
try {
if (p.getName().equals(ApplicationFacade.SESSION_ID))
rootjsonObject.put((String) p.getName(), (String) p.getValue());
else
jsonObject.put((String) p.getName(), (String) p.getValue());
} catch (JSONException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
}
try {
rootjsonObject.put(RootName, jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
return rootjsonObject;
}
我试过用How to make a nested Json object in Java?给出的方法
这就是我使用链接中提到的方法提出请求的方式。
public ArrayList<NameValuePair> getJsonObjectfromNameValueList(ArrayList<NameValuePair> _params, String RootName){
ArrayList<NameValuePair> arrayList = new ArrayList<NameValuePair>();
JSONObject jsonObject = new JSONObject();
if (_params != null) {
if (!_params.isEmpty()) {
for (NameValuePair p : _params) {
try {
if (p.getName().equals(ApplicationFacade.SESSION_ID))
arrayList.add(new BasicNameValuePair((String) p.getName(), (String) p.getValue()));
else
jsonObject.put((String) p.getName(), (String) p.getValue());
} catch (JSONException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
}
arrayList.add(new BasicNameValuePair(RootName, jsonObject.toString()));
return arrayList;
}
进行上述更改后我得到的响应是这样的:
{"session_id"=>"958c7dee-f12c-49ec-ab0c-932e9a4ed173",
"user"=>"[gender=male]",
"splat"=>["update_profile.json"],
"captures"=>["update_profile.json"]}
非常接近,但“性别=男性”是不可取的。我需要将这些参数盲目地传递给另一个服务,所以我需要正确处理它们。
我想要在我的 sinatra 服务中使用的参数如下。
{"session_id" : "958c7dee-f12c-49ec-ab0c-932e9a4ed173",
"user":
{
"gender" : "male"
}
}
【问题讨论】:
-
你可以试试 application/json 作为 ContentType 吗?
-
我已经做到了。在我的 sinatra 服务中看不到参数。虽然我可以使用 - request.body.read 来阅读它们,但这似乎是一种解决方法。
-
我不明白解释和问题是什么?你用了很多“这个”这个词,但我不知道你指的是什么。
-
我做了一些语言更改。希望有帮助