Reading a Web resource's headers and content:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class MainClass {
public static void main(String[] args) {
try {
URL url = new URL("http://www.rntsoft.com/");
URLConnection urlConnection = url.openConnection();
Map> headers = urlConnection.getHeaderFields();
Set>> entrySet = headers.entrySet();
for (Map.Entry> entry : entrySet) {
String headerName = entry.getKey();
System.out.println("Header Name:" + headerName);
List headerValues = entry.getValue();
for (String value : headerValues) {
System.out.print("Header value:" + value);
}
System.out.println();
}
InputStream inputStream = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = bufferedReader.readLine();
while (line != null) {
System.out.println(line);
line = bufferedReader.readLine();
}
bufferedReader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Header Name:Content-Length
Header value:329495
Header Name:X-Powered-By
Header value:ASP.NET
Header Name:ETag
Header value:"30d67746a17c71:11e5"
Header Name:null
Header value:HTTP/1.1 200 OK
Header Name:Date
Header value:Fri, 26 Jan 2007 17:02:42 GMT
Header Name:Accept-Ranges
Header value:bytes
Header Name:Content-Type
Header value:text/html
Header Name:Server
Header value:Microsoft-IIS/6.0
Header Name:Last-Modified
Header value:Mon, 04 Dec 2006 06:04:11 GMT
Header Name:Content-Location
Header value:http://www.rntsoft.com/index.htm