読者です 読者をやめる 読者になる 読者になる

or1ko's diary

日々を書きます

HTTP クライアント GETの例

Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;


public class SampleGetHttpClient {

	public static void main(String[] args) throws IOException {
		String url = "http://localhost:8080/";
		HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                // HTTPSの場合はHttpsURLConnectionにキャストすれば良いらしい
		connection.setRequestMethod("GET");
		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);
		}
	}
}