// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.stream.Stream;

public class Http11 {
    public static void testGET() throws IOException, InterruptedException {
        HttpClient client = HttpClient.newBuilder().build();
        HttpRequest request = HttpRequest.newBuilder().uri(URI.create("http://localhost:81/test.txt")).GET().build();
        HttpResponse<Stream<String>> response = client.send(request, BodyHandlers.ofLines());
        response.body().forEach(line -> System.out.println(line));
    }
    public static void testPOST() throws IOException, InterruptedException {
        HttpClient client = HttpClient.newBuilder().build();
        HttpRequest request = HttpRequest.newBuilder().uri(URI.create("http://localhost:81/test.php")).POST(BodyPublishers.ofString("f=123")).header("Content-Type", "application/x-www-form-urlencoded").build();
        HttpResponse<Stream<String>> response = client.send(request, BodyHandlers.ofLines());
        response.body().forEach(line -> System.out.println(line));
    }
    public static void main(String[] args) throws IOException, InterruptedException {
        testGET();
        testPOST();
    }
}
