在 java 中使用 HttpURLConnection 发布数组

Posting array in with HttpURLConnection in java

我们有这段代码,我们正在使用它来 post 从 Android 应用程序到 .Net Rest 服务的数据。后端是数组的字段之一。 Swagger 将其指定为

modelbinding Array[integer]

我们应该如何将整数值数组放入 urlParameters 中,这样我们才能 post 它?

String urlParameters = "field1=abc&field2=def";

URL url = new URL(targetURL);

connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);

// Send request
writer = new DataOutputStream (connection.getOutputStream ());
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(writer, "UTF-8"));
bufferedWriter.write(urlParameters);
bufferedWriter.flush ();
bufferedWriter.close (); 

使用Json格式是发送数据的最佳方式。您可以将 json 数组中的数据然后 json 数组转换为字符串。现在您的字符串(以 json 格式表示)可以轻松发送。