通过HttpURLConnection我可以轻松的获取网站数据:
public class NewSocket {
public static String getNetData(String host) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(host).openConnection();
InputStream inputStream = conn.getInputStream();
int len = 1;
byte[] buffer = new byte[1024];
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
return new String(byteArrayOutputStream.toByteArray());
}
public static void main(String[] args) {
try {
System.out.println(NewSocket.getNetData("http://localhost:8080/videoweb"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
但是通过socket的话,我不知道怎么访问web数据。
public class OtherNewSocket {
public static String getNetData(String host, int port) throws IOException {
Socket socket = new Socket(host, port);
byte[] buffer = new byte[1024];
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int len = 0;
while ((len = socket.getInputStream().read(buffer)) != -1) {
byteArrayOutputStream.write(buffer);
}
return new String(byteArrayOutputStream.toByteArray());
}
public static void main(String[] args) {
try {
System.out.println(OtherNewSocket.getNetData("localhost", 8080));
} catch (IOException e) {
e.printStackTrace();
}
}
}
求指教,然后我想知道通过url访问和通过socket访问有什么不同点,我理解的就是,通过url访问访问的直接是某个项目网页地址,而通过socket访问呢,则是端对端的访问,也就是访问的其实是目标服务器的某一端口上的进程,但是如果要具体访问进程上的项目,也就是默认欢迎页面index.jsp,又该如何做呢