Технологии Java
Работа с сетью
getScheme() | scheme | ||
getSchemeSpecificPart() | scheme‑specific part | ||
getAuthority() | [user‑info@]host[:port] | ||
getUserInfo() | user‑info | ||
getHost() | host | ||
getPort() | port | ||
getPath() | path | ||
getQuery() | query | ||
getFragment() | fragment |
HttpClient client = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_2) .proxy(ProxySelector.of( new InetSocketAddress("proxy.itmo.ru", 3128))) .followRedirects( HttpClient.Redirect.NORMAL) .cookieHandler(new CookieManager()) .authenticator(new Authenticator(){...}) .build();
HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://www.kgeorgiy.info/hello")) .version(HttpClient.Version.HTTP_2) .header("Cache‑Control", "no‑cache") .header("User‑Agent", "hello") .timeout(Duration.ofSeconds(3)) .POST(HttpRequest.BodyPublishers .ofString("world", StandardCharsets.UTF_8)) .build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString( StandardCharsets.UTF_8)); if (response.statusCode() == HttpURLConnection.HTTP_OK ) { System.out.println(response.body()); } else { // Fail }
HttpHandler helloHandler = t -> { String name; try (IS is = t.getRequestBody()) { name = new BR(new ISR(is, SC.UTF_8)).readLine(); } byte[] response = ("Hello, " + name) .getBytes(SC.UTF_8); t.sendResponseHeaders( HttpURLConnection.HTTP_OK, response.length); try (OutputStream os = t.getResponseBody()) { os.write(response); } };
HttpServer server = HttpServer.create( new InetSocketAddress(8080), // порт 0 // размер очереди ); server.createContext("/hello", helloHandler); server.setExecutor(null); // по умолчанию server.start();