Path: blob/master/test/jdk/java/net/URLConnection/GetResponseCode.java
41149 views
/*1* Copyright (c) 2001, 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 419181526* @library /test/lib27* @summary Check that getResponseCode doesn't throw exception if http28* respone code is >= 400.29*/30import java.net.*;31import java.io.*;3233import jdk.test.lib.net.URIBuilder;3435public class GetResponseCode implements Runnable {3637ServerSocket ss;3839/*40* Our "http" server to return a 40441*/42public void run() {43try {44Socket s = ss.accept();4546PrintStream out = new PrintStream(47new BufferedOutputStream(48s.getOutputStream() ));4950/* send the header */51out.print("HTTP/1.1 404 Not Found\r\n");52out.print("Content-Type: text/html; charset=iso-8859-1\r\n");53out.print("Connection: close\r\n");54out.print("\r\n");55out.print("<HTML>");56out.print("<HEAD><TITLE>404 Not Found</TITLE></HEAD>");57out.print("<BODY>The requested URL was not found.</BODY>");58out.print("</HTML>");59out.flush();6061/*62* Sleep added to avoid connection reset63* on the client side64*/65Thread.sleep(1000);66s.close();67ss.close();68} catch (Exception e) {69e.printStackTrace();70}71}7273GetResponseCode() throws Exception {7475/* start the server */76ss = new ServerSocket();77ss.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));78(new Thread(this)).start();7980/* establish http connection to server */81URL url = URIBuilder.newBuilder()82.scheme("http")83.loopback()84.port(ss.getLocalPort())85.path("/missing.nohtml")86.toURL();8788HttpURLConnection http = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);8990int respCode = http.getResponseCode();9192http.disconnect();9394}9596public static void main(String args[]) throws Exception {97new GetResponseCode();98}99100}101102103