android-studio - Android - 如何在正文中使用带有元素标签的 Volley HTTP Post
问题描述
我一直在试图弄清楚如何在正文中使用带有 HTML 元素标签的 Volley,但可以使用一些帮助。
例如,对于我正在使用的 API,使用 POST 创建用户所需的格式如下:
{
"username":"",
"password":"",
"email":"someone@example.invalid",
"first_name":"John",
"last_name":"Doe",
"phone_number":"202-555-0113",
"address":"123 Road Name",
"city":"Jamesetown",
"state":"AZ",
"postal_code":"12345",
"country":"United States",
}
...我能够在 Android 端格式化并成功处理 POST,如下所示:
@Override
public byte[] getBody() throws AuthFailureError {
Map<String, String> bodyKeyValue = new HashMap<>();
bodyKeyValue.put("username", accountName);
bodyKeyValue.put("password", accountPassword);
bodyKeyValue.put("email", email);
bodyKeyValue.put("first_name", first);
bodyKeyValue.put("last_name", last);
// etc.
return new JSONObject(bodyKeyValue).toString().getBytes();
}
但是,当涉及到需要使用元素标签格式化的 POST 时,我似乎无法弄清楚在我的 Volley 正文中将如何格式化。如何将其放入 MAP 对象中?在任何回应中,如果 getBodyContentType 也需要更改,您能否告诉我?标头内容类型应保持不变。谢谢!
<sci_request version="1.2">
<data_service>
<targets>
<device id="1234-5678" />
</targets>
<requests>
<device_request target_name="myTarget">
some request string value
</device_request>
</requests>
</data_service>
</sci_request>
解决方案
我发现这比预期的要容易得多......只需按如下方式更改正文:
@Override
public byte[] getBody() throws AuthFailureError {
String data =
"<sci_request version=\"1.2\">" +
"<data_service>" +
"<targets>" +
"<device id=\"1234-5678\" />" +
"</targets>" +
"<requests>" +
"<device_request target_name=\"myTarget\">" +
"some request string value" +
"</device_request>" +
"</requests>" +
"</data_service>" +
"</sci_request>";
return data.getBytes();
}
请注意,这是一个 Volley StringRequest,并非所有代码都显示在此处。
推荐阅读
- c - 如何避免在 C 中使用字符串的递归函数中的分段错误?
- javascript - 如何在特定的 Wordpress 页面上运行 JavaScript 函数?
- postgresql - 如何在 PostgreSQL 中对使用 date_trunc 函数的表达式创建索引?
- python - 还是 Python 中的 print 语句中的关键字?
- ruby-on-rails - 在 Rails 中使用一对多关系将种子数据从 YML 加载到 db
- jquery - Watson 文本转语音:凭据 URL
- sql - 删除查询结果之外的所有内容
- c++ - 如何访问 CGAL 3D 三角剖分中的构面?
- python - 如何从 Cloud Bigtable 中仅读取某些列族?
- node.js - Node js docker远程调试chrome