我有服务器,它接受 int 或一个 int 的列表。当我发送 int 时,它工作得很好,但是当我尝试发送List<Integer>
或int[]
时,响应总是错误(code 400
)。如何发送 int 列表?这是我的代码:
url = new URL(adress);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(10000);
urlConnection.setReadTimeout(10000);
urlConnection.setRequestProperty("Content-Type","application/json");
"android.schoolportal.gr");
urlConnection.connect();
JSONObject jsonParam = new JSONObject();
jsonParam.put("categories_okpd_2", list);
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(jsonParam.toString());
out.close();
我尝试list
像:
int myInt = 1;
List<Integer> list = new ArrayList<Integer>();
list.add(myInt);
和
int[] list = new int[5];
但它总是导致错误 code:400
.
HTTP 状态 400 表示错误请求:您向服务器发送了它无法解析的内容(您发送包裹在对象中的列表,服务器等待纯列表)。
一开始,尝试在客户端使用列表记录 json。要以 json 格式发送列表以更好地将其包装在类中:
{
"list": [0, 4, 5]
}
你需要将列表解析为 json,然后发送它。这是关于如何将列表解析为 json 格式的类似答案。