Path: blob/master/test/jdk/java/net/HttpURLConnection/HttpResponseCode.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 447309226* @library /test/lib27* @summary Method throws IOException when object should be returned28* @run main HttpResponseCode29* @run main/othervm -Djava.net.preferIPv6Addresses=true HttpResponseCode30*/31import java.net.*;32import java.io.*;33import jdk.test.lib.net.URIBuilder;3435public class HttpResponseCode implements Runnable {36ServerSocket ss;37/*38* Our "http" server39*/40public void run() {41try {42Socket s = ss.accept();4344BufferedReader in = new BufferedReader(45new InputStreamReader(s.getInputStream()) );46String req = in.readLine();4748PrintStream out = new PrintStream(49new BufferedOutputStream(50s.getOutputStream() ));515253/* send the header */54out.print("HTTP/1.1 403 Forbidden\r\n");55out.print("\r\n");56out.flush();5758s.close();59ss.close();60} catch (Exception e) {61e.printStackTrace();62}63}6465HttpResponseCode() throws Exception {66/* start the server */67InetAddress loopback = InetAddress.getLoopbackAddress();68ss = new ServerSocket();69ss.bind(new InetSocketAddress(loopback, 0));70(new Thread(this)).start();7172/* establish http connection to server */73URL url = URIBuilder.newBuilder()74.scheme("http")75.loopback()76.port(ss.getLocalPort())77.path("/missing.nothtml")78.toURL();79URLConnection uc = url.openConnection(Proxy.NO_PROXY);80int respCode1 = ((HttpURLConnection)uc).getResponseCode();81((HttpURLConnection)uc).disconnect();82int respCode2 = ((HttpURLConnection)uc).getResponseCode();83if (respCode1 != 403 || respCode2 != 403) {84throw new RuntimeException("Testing Http response code failed");85}86}8788public static void main(String args[]) throws Exception {89new HttpResponseCode();90}91}929394