ネットの記事をいろいろ参考にしながら、Java 1.8 の標準 API だけで作ってみた。
import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; public class MainPost { public static void main(String[] args) { String urlStr = "https://httpbin.org/post"; HttpURLConnection urlConn = null; BufferedReader reader = null; try { URL url = new URL(urlStr); urlConn = (HttpURLConnection)url.openConnection(); // Post 送信 urlConn.setRequestMethod("POST"); urlConn.setDoOutput(true); OutputStream out = urlConn.getOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(out, StandardCharsets.UTF_8); String postData = "param1=value1¶m2=value2"; writer.write(postData); writer.close(); // Post の response を受信 int status = urlConn.getResponseCode(); System.out.println("HTTP Status:" + status); if (status == HttpURLConnection.HTTP_OK) { InputStream in = urlConn.getInputStream(); reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)); StringBuilder res = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { res.append(line).append(System.lineSeparator()); } System.out.println(res); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } if (urlConn != null) { urlConn.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } } }