Java 如何将数组传递给POST API?
在我的Android应用程序中,我需要将数组作为body(有效负载信息)发送到POST url 在body中,有两个参数:Java 如何将数组传递给POST API?,java,android,post,Java,Android,Post,在我的Android应用程序中,我需要将数组作为body(有效负载信息)发送到POST url 在body中,有两个参数: 1. "env" : "dev" 2. "dNumber" : tn("+1232323"); // here I need to send an array. 编辑问题:我需要像[“123131”,“4545545”]这样的数组发送电话 我将数组作为创建的JSON数组传递,并将其转换为字符串并传递 private String tn(String tn) {
1. "env" : "dev"
2. "dNumber" : tn("+1232323"); // here I need to send an array.
编辑问题:我需要像[“123131”,“4545545”]这样的数组发送电话
我将数组作为创建的JSON数组传递,并将其转换为字符串并传递
private String tn(String tn) {
String json = "";
try {
JSONArray jsonArray = new JSONArray();
jsonArray.put(0, tn);
json = jsonArray.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
完整代码为:
try {
URL url;
HttpURLConnection urlConnection;
url = new URL(makeCallUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Authorization", String.format("%s %s", "Basic", secretKey));
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true);
urlConnection.connect();
// Setup the body of the url
JSONObject json = new JSONObject();
json.put("env", "dev");
json.put("destNumbers", tn("+123123"));
// Write the body on the wire
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream()));
writer.write(json.toString());
writer.flush();
writer.close();
} catch (IOException e) {
Log.d(TAG, "IOException:" + e.getMessage());
e.printStackTrace();
}
如果我尝试这个,我得到了400,错误的请求异常。
请帮助我将数组传递给POST api我使用JSONArray解决了问题并传递了数组
// creating json array
JSONArray numberArray = new JSONArray();
numberArray.put(0, tn);
// send the array with payload
JSONObject json = new JSONObject();
json.put("env", "DEV");
json.put("destNumbers", numberArray);
现在我得到如下数组:
destNumbers=[“34343”,“3434334]更新您的tn()方法。它应该返回JSONArray,而不是返回字符串
private JSONArray tn(String tn) {
JSONArray jsonArray = new JSONArray();
try {
jsonArray.put(0, tn);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonArray ;
}
尽管仍然出现400错误请求错误,但请使用json确认并验证请求有效负载。什么是tn--json.put(“destNumbers”,tn(+123123”);?400可能意味着任何东西。请查看服务器日志并查看失败的原因(假设您的服务器)。如果不是您的服务器,请检查文档,确保您以实际期望的格式发送数据。此外,从您发布的内容中,我看不到任何需要数组的内容。@MilanPansuriya,创建json数组format@M.A.Murali你能在你的问题中加入你的tn方法吗