通过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,又该如何做呢
你需要看下http协议的底层啊,
live.html是一个资源路径啊,
获取别的就写别的了,只是举个例子。
你可以参看http协议
模拟HTTP发送一个get请求即可
[code="java"]
package com.iteye.wenda.socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class HttpGetWebPage {
public static void main(String[] args) {
try {
Socket socket = new Socket("mdcc.csdn.net", 80);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
out.print("GET /live.html HTTP/1.1");
out.println("/n");
String rep = "";
while(null!=(rep = reader.readLine())){
System.out.println(rep);
}
out.flush();
out.close();
reader.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
[/code]
别忘给分啊,兄弟!