Path: blob/master/test/jdk/com/sun/net/httpserver/EchoHandler.java
41152 views
/*1* Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223import java.io.IOException;24import java.io.InputStream;25import java.io.OutputStream;26import java.nio.charset.StandardCharsets;2728import com.sun.net.httpserver.Headers;29import com.sun.net.httpserver.HttpExchange;30import com.sun.net.httpserver.HttpHandler;3132/**33* Implements a basic static EchoHandler for an HTTP server34*/35public class EchoHandler implements HttpHandler {36public void handle (HttpExchange t)37throws IOException38{39InputStream is = t.getRequestBody();40Headers map = t.getRequestHeaders();41String fixedrequest = map.getFirst ("XFixed");4243// return the number of bytes received (no echo)44String summary = map.getFirst ("XSummary");45OutputStream os = t.getResponseBody();46byte[] in;47in = is.readAllBytes();48if (summary != null) {49in = Integer.toString(in.length).getBytes(StandardCharsets.UTF_8);50}51if (fixedrequest != null) {52t.sendResponseHeaders(200, in.length == 0 ? -1 : in.length);53} else {54t.sendResponseHeaders(200, 0);55}56os.write(in);57close(t, os);58close(t, is);59}6061protected void close(OutputStream os) throws IOException {62os.close();63}64protected void close(InputStream is) throws IOException {65is.close();66}67protected void close(HttpExchange t, OutputStream os) throws IOException {68close(os);69}70protected void close(HttpExchange t, InputStream is) throws IOException {71close(is);72}73}747576