zoukankan      html  css  js  c++  java
  • JAVA编写的使用Socket模拟Http的GET操作

    JAVA编写的使用Socket模拟Http的GET操作看后就很容易理解Web浏览器的原理了。

    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.net.Socket;
    
    public class TestSocket {
      String host = "www.javathinker.org";
      int port = 80;
      Socket socket;
    
      public void createSocket() throws Exception {
        socket = new Socket("www.163.com", 80);
      }
    
      public void communicate() throws Exception {
        StringBuffer sb = new StringBuffer("GET / HTTP/1.1/r/n");
        sb.append("Host: <A href="www.163.com" mce_href="www.163.com" target=_blank>www.163.com</A>/r/n");
        sb.append("Connection: Keep-Alive/r/n");
        sb.append("Accept: */*/r/n/r/n");
    
        // 发出HTTP请求
        OutputStream socketOut = socket.getOutputStream();
        socketOut.write(sb.toString().getBytes());
        socket.shutdownOutput(); // 关闭输出流
    
        // 接收响应结果
        System.out.println(socket);
    
        InputStream socketIn = socket.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(socketIn));
        String data;
        while ((data = br.readLine()) != null) {
          System.out.println(data);
        }
        socket.close();
      }
    
      public static void main(String args[]) throws Exception {
        TestSocket client = new TestSocket();
        client.createSocket();
        client.communicate();
      }
    
    }


  • 相关阅读:
    [整理]Cadence 生成带有网络追踪的 PDF 原理图
    [整理]FSM 有限状态机
    [原创]Quartus 中调用 Modelsim 波形仿真
    [原创]SPI 协议介绍以及基于 Verilog 的 IP 核实现
    [原创]Verilog 代码编程规范(个人用)
    [算法]线段树
    [算法]tarjan
    poj3280
    poj 3258 River Hopscotch
    [poj 1251]Jungle Roads
  • 原文地址:https://www.cnblogs.com/leixiaohua1020/p/3902166.html
Copyright © 2011-2022 走看看