Here you can find the source of getInputStream(HttpURLConnection conn)
public static InputStream getInputStream(HttpURLConnection conn)
//package com.java2s; /******************************************************************************* * Copyright (c) 2005-2011 eBay Inc./*from w w w. ja va 2 s. c om*/ * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; public class Main { public static InputStream getInputStream(HttpURLConnection conn) { return getInputStream(conn, false); //only get valid inputStream } public static InputStream getInputStream(HttpURLConnection conn, boolean includeError) { InputStream stream = null; try { int code = HttpURLConnection.HTTP_OK; try { code = conn.getResponseCode(); } //catch (java.io.FileNotFoundException exp) { catch (java.io.IOException exp) { //this exception is due to JDK 1.3.1 bug when 401 returns int index = 0; String errMessage = null; while ((errMessage = conn.getHeaderField(index)) != null) { if (errMessage.indexOf(" 401 ") != -1) { code = HttpURLConnection.HTTP_UNAUTHORIZED; break; } index++; } } if (code == HttpURLConnection.HTTP_UNAUTHORIZED) { //create a stream for sending the default login page stream = new ByteArrayInputStream(getLoginForm(conn.getURL().toString()).getBytes()); } else { stream = conn.getInputStream(); if (stream == null && includeError) stream = conn.getErrorStream(); } } catch (IOException e) { } return stream; } static String getLoginForm(String urlStr) { //create default login page for HttpRequest login String loginForm = "<H>Logon to : " + getURLHost(urlStr) + "</H>" + "<FORM name=login method=AUTHORIZATION action=" + urlStr + ">" + "<TABLE><TR>" + "<TD>User Name : </TD>" + "<TD><INPUT size=10 name=username></TD>" + "</TR><TR>" + "<TD>Password : </TD>" + "<TD><INPUT type=password size=10 name=password></TD>" + "</TR></TABLE>" + "<INPUT type=submit value=Submit>" + "</FORM>"; return loginForm; } /** * Returns the URL host */ static public String getURLHost(String url_str) { if (url_str == null) return null; String s = url_str; int i = s.indexOf("://"); if (i > -1) { s = s.substring(i + 3); } i = s.indexOf('/'); if (i > -1) { s = s.substring(0, i); } return s; } }