JSONObject postData = new JSONObject(); try { postData.put("key1", value1); postData.put("key2", value2); postData.put("key3", value3); } catch (JSONException e) { e.printStackTrace(); }
URL url = new URL("http://your-server-url.com/api"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(postData.toString()); wr.flush();
@Override public Response serve(IHTTPSession session) { String data = null; try { session.parseBody(null); data = session.getQueryParameterString(); JSONObject receivedData = new JSONObject(data);
// 操作receivedData对象,然后构建响应JSON对象
JSONObject responseObj = new JSONObject();
responseObj.put("keyA", valueA);
responseObj.put("keyB", valueB);
return newFixedLengthResponse(Response.Status.OK, "application/json", responseObj.toString());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
以上代码示例展示了使用Android客户端向服务器发送JSON数据的方法,以及如何在服务器上处理接收到的JSON数据。