or1ko's diary

日々を書きます

HTTPクライアント POSTの例

http://localhost:8080にPOSTでアクセスして、
レスポンスをUTF-8エンコーディングしてコンソールに表示する。

public class SamplePostHttpClient {

	public static void main(String[] args) throws IOException {
		String url = "http://localhost:8080/";
		HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                // HTTPSの場合、HttpsUrlConnectionにキャストすれば良い
		connection.setRequestMethod("POST");
		connection.setDoOutput(true);

		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8));
		writer.write("Hello World");
		writer.flush();

		try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
			StringBuilder builder = new StringBuilder();
			String line;
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}
			System.out.println(builder);
		}
	}
}