I am trying to read html site using below code,System hanging any hints please:
package com.test;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.net.Socket;
import javax.net.SocketFactory;
import java.net.InetAddress;
public class writingFile {
public static void main(String a[]) throws Exception {
SocketFactory factory=SocketFactory.getDefault();
Socket socket=new Socket(InetAddress.getByName("java.sun.com"), 80);
BufferedWriter out=new BufferedWriter(new FileWriter("C://test.html"));
int data;
while((data=socket.getInputStream().read()) != -1) {
out.write((char)data);
out.flush();
}
}
}
Regards,
Raj
解决方案
This is HTTP. You can't just open a socket and start reading something. You have to be polite to the server and send a request first:
socket.getOutputStream().write("GET /index.html HTTP/1.0\n\n".getBytes());
socket.getOutputStream().flush();
Then read a HTTP response, parse it, and get your html page back.
EDIT I wrote what to do with sockets only because it was the immediate problem of the OP. Using URLConnection is the correct way, as answered by @Mike Deck.