LoginSignup
4
2

More than 3 years have passed since last update.

[java] HttpURLConnection POST

Posted at

使い方

以下の通りである。

        try {
            //コネクション
            URL url = new URL("URL");
            httpURLConnection_ = (HttpURLConnection) url.openConnection();
            httpURLConnection_.setDoOutput(true);  //POST可能にする
            httpURLConnection_.connect();

            //送信したいデータ
            String param = "param1=1";

            //リクエストボディに送信したいデータを書き込む
            OutputStream os = httpURLConnection_.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(param);
            writer.flush();
            writer.close();

            //クローズ処理
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

サーバ側で値を取得するときは以下のようにする。(サーバはHttpServletを継承したjavaファイル)

public class Server extends HttpServlet{
    public void doPost(HttpServletRequest request, 
                       HttpServletResponse response)
                       throws IOException, ServletException{
        request.getParameter("param1");
    }
}

感想

見かけは難しく見えたが、予想より簡単に実装できた。結構使うらしいので覚えておきたい。

参考URL

4
2
0

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
4
2