LoginSignup
10

More than 5 years have passed since last update.

JavaでJSONをPOST

Last updated at Posted at 2018-06-05

JavaでJSONをPOSTするコード

一時的に持っておきたいデータをDBに保存するまでもないので、JSONのStringでポストして共有できるようにしました。

postJSON
    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();
        }
    }

サーブレット側のコード

POSTされたデータを受け取って JSONArray と JSONObject にして保管します。

doPost
    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();
        }
    }

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10