使用Java发送JSON POST请求

使用Java代码进行POST JSON。

由於暫時無需將數據存儲到數據庫中,我們使用JSON字符串進行發送和共享。

    public String postJson(String json, String path) {
        HttpURLConnection uc;
        try {
            URL url = new URL("http://host"+path);
            uc = (HttpURLConnection) url.openConnection();
            uc.setRequestMethod("POST");
            uc.setUseCaches(false);
            uc.setDoOutput(true);
            uc.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            OutputStreamWriter out = new OutputStreamWriter(
                new BufferedOutputStream(uc.getOutputStream()));
            out.write(json);
            out.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
            String line = in.readLine();
            String body = "";
            while (line != null) {
                body = body + line;
                line = in.readLine();
            }
            uc.disconnect();
            return body;
        } catch (IOException e) {
            e.printStackTrace();
            return "client - IOException : " + e.getMessage();
        }
    }

Servlet代码

将接收到的POST数据保存为JSONArray和JSONObject。

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        BufferedReader br = new BufferedReader(request.getReader());
        String line = br.readLine();
        String body = "";
        if (line != null) {
            body = body + line;
            line = br.readLine();
        }
        PrintWriter out = response.getWriter();
        out.println("{\"status\":\"OK\"}");
        out.flush();
        out.close();

        try {
            LinkedList todo = new LinkedList();
            JSONArray ja = new JSONArray(body);
            for (int i = 0; i < ja.length(); i++) {
                JSONObject tdj = (JSONObject) ja.get(i);
                //処理追加                        
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
bannerAds