Path: blob/master/test/jdk/java/net/URL/GetContent.java
41149 views
/*1* Copyright (c) 1998, 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*/2223/**24* @test25* @bug 414531526* @library /test/lib27* @summary Test a read from nonexistant URL28* @run main GetContent29* @run main/othervm -Djava.net.preferIPv6Addresses GetContent30*/3132import java.net.*;33import java.io.*;34import jdk.test.lib.net.URIBuilder;3536public class GetContent implements Runnable {3738ServerSocket ss;3940public void run() {41try (Socket s = ss.accept()) {42s.setTcpNoDelay(true);4344PrintStream out = new PrintStream(45new BufferedOutputStream(46s.getOutputStream() ));4748out.print("HTTP/1.1 404 Not Found\r\n");49out.print("Connection: close\r\n");50out.print("Content-Type: text/html; charset=iso-8859-1\r\n");51out.print("\r\n");52out.flush();53out.print("<HTML><BODY>Sorry, page not found</BODY></HTML>");54out.flush();5556// wait for client to read response - otherwise http57// client get error and re-establish connection58Thread.sleep(2000);5960} catch (Exception e) {61e.printStackTrace();62} finally {63try { ss.close(); } catch (IOException unused) {}64}65}6667GetContent() throws Exception {68InetAddress loopback = InetAddress.getLoopbackAddress();69ss = new ServerSocket();70ss.bind(new InetSocketAddress(loopback, 0));7172Thread thr = new Thread(this);73thr.start();7475boolean error = true;76try {77java.net.URL url = URIBuilder.newBuilder()78.scheme("http")79.host(ss.getInetAddress())80.port(ss.getLocalPort())81.path("/no-such-name")82.toURL();83Object obj = url.openConnection(Proxy.NO_PROXY)84.getContent();85InputStream in = (InputStream) obj;86byte buff[] = new byte[200];87int len = in.read(buff);88} catch (IOException ex) {89error = false;90}9192if (error)93throw new RuntimeException("No IOException generated.");94}9596public static void main(String args[]) throws Exception {97new GetContent();98}99}100101102