[java] HttpURLConnection POST

How to use

It is as follows.

        try {
 //コネクション
            URL url = new URL("URL");
            httpURLConnection_ = (HttpURLConnection) url.openConnection();
 httpURLConnection_.setDoOutput (true); // Enable 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();
        }

To get the value on the server side, do as follows. (The server is a java file that inherits HttpServlet)

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

Impressions

It looked difficult, but it was easier to implement than expected. It seems to be used quite a lot, so I want to remember it.

Reference URL

http://konkea.hatenablog.com/entry/2016/10/20/181856

Recommended Posts

[java] HttpURLConnection POST
POST Json in Java ~ HttpURLConnection ~
POST JSON in Java
Java
Java
How to use Java HttpClient (Post)
Upload a file using Java HttpURLConnection
Screen transition by Post method [Java]
Studying Java ―― 3
[Java] array
Java protected
[Java] Annotation
Get the result of POST in Java
[Java] Module
Java array
Studying Java ―― 9
Java scratch scratch
Java tips, tips
Java methods
First post
Java method
java (constructor)
Java array
[Java] ArrayDeque
java (override)
java (method)
Java Day 2018
Java string
java (array)
Java static
Java serialization
java beginner 4
JAVA paid
Studying Java ―― 4
Java (set)
java shellsort
[Java] compareTo
Studying Java -5
java reflexes
java (interface)
Java memorandum
☾ Java / Collection
Java array
Studying Java ―― 1
[Java] Array
[Java] Polymorphism
Studying Java # 0
Java review
java framework
Java features
[Java] Inheritance
FastScanner Java
Java features
java beginner 3
Java memo
java (encapsulation)
Java inheritance
[Java] Overload
Java basics
Decompile Java
[Java] Annotation