fzw172672421 2011-11-04 16:58
浏览 287
已采纳

socket获取web网站数据的方法

通过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,又该如何做呢

  • 写回答

4条回答 默认 最新

  • khan7923 2011-11-05 11:24
    关注

    你需要看下http协议的底层啊,
    live.html是一个资源路径啊,
    获取别的就写别的了,只是举个例子。
    你可以参看http协议

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择
  • ¥15 这款软件是什么?需要能满足我的需求
  • ¥15 SpringSecurityOauth2登陆前后request不一致