【发布时间】:2021-05-25 05:30:15
【问题描述】:
这是我第一次在android(Java)中使用改造,我不知道如何做post api
在邮递员中,我使用请求正文作为原始 JSON
{ “描述”:“aaaaaa”, "reportedpriority_description": "Elevé", “报告人”:“zz”, “资产”:“111”, “受影响的人”:“艾哈迈德” }
有人可以帮助我提供代码示例吗?它返回空响应体
【问题讨论】:
这是我第一次在android(Java)中使用改造,我不知道如何做post api
在邮递员中,我使用请求正文作为原始 JSON
{ “描述”:“aaaaaa”, "reportedpriority_description": "Elevé", “报告人”:“zz”, “资产”:“111”, “受影响的人”:“艾哈迈德” }
有人可以帮助我提供代码示例吗?它返回空响应体
【问题讨论】:
void requestcall(){
try
{
HashMap respMap = new HashMap<>();
respMap.put("Key1", "Value1");
respMap.put("Key2", "Value2");
respMap.put("Key3", "Value3");
String resultString = convertToJson(respMap);
sendToServer(resultString);
}
catch (Exception e)
{ }
}
public static String convertToJson(HashMap<String, String> respMap)
{
JSONObject respJson = new JSONObject();
JSONObject respDetsJson = new JSONObject();
Iterator mapIt = respMap.entrySet().iterator();
try
{
while (mapIt.hasNext()) {
HashMap.Entry<String, String> entry = (HashMap.Entry) mapIt.next();
respDetsJson.put(entry.getKey(), entry.getValue());
}
//change according to your response
respJson.put("RESPONSE", respDetsJson);
}
catch (JSONException e)
{
return "";
}
return respJson.toString();
}
【讨论】:
您可以通过两种方式发送 Post 方法的正文,您可以创建所需格式的 JSON 字符串。或者,您可以简单地创建一个与 JSON 键具有相同字段名称的模型类,然后在发送请求时为其初始化值。
模型类:
class Example {
var description: String? = null
var reportedpriority_description: String? = null
var reportedby: String? = null
var assetnum: String? = null
var affectedperson: String? = null
}
初始值:
val obj = Example()
obj.description = "aaaaaa"
// and so on
然后您可以将对象传递给您的 POST 方法。
您可以参考documentations 了解如何编写 API 方法。
希望这对你有用!
【讨论】: