a1670131049
2019-04-10 22:19
采纳率: 50%
浏览 427
已采纳

java 仿浏览器读取web服务器数据

1:写的程序读取不到文件,web服务器用的是tomcat,已经打开了,用浏览器也能正常访问到

        Socket s=new Socket("127.0.0.1",8080);
        PrintWriter pw=new PrintWriter(s.getOutputStream(),true);
        pw.println("GET /myweb/1.html HTTP/1.1");
        pw.print("Accept: */*");
        pw.println("Host: 127.0.0.1:8080");
        pw.println("Connection: close");
        pw.println();

        InputStream ins=s.getInputStream();
        byte[] buf=new byte[1024];
        int len=ins.read(buf);
        String str=new String(buf,0,len);
        System.out.println(str);

        s.close();

运行结果:

HTTP/1.1 400 Bad Request
Server: Apache-Coyote/1.1
Transfer-Encoding: chunked
Date: Wed, 10 Apr 2019 14:11:40 GMT
Connection: close

0
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • 林兴洋 2019-04-10 22:39
    已采纳

    要看一下Html 请求头和响应头的格式

    请求头需要两个换行
    后面的每一行需要一个换行

    package net.linxingyang.test;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.InetAddress;
    import java.net.InetSocketAddress;
    import java.net.Socket;
    import java.net.UnknownHostException;
    
    public class TestHttp {
    
        public static void main(String[] args) throws UnknownHostException, IOException {
    
    
            Socket socket = new Socket();
            socket.connect(new InetSocketAddress(InetAddress.getByName("www.baidu.com"), 80));
    
            OutputStream os = socket.getOutputStream();
            os.write("GET / HTTP/1.1\n\n".getBytes());
            // os.write("other header \n".getBytes());
    
            InputStream is = socket.getInputStream();
            int length = -1;
            byte[] bytes = new byte[1024];
            while (-1 != (length = is.read(bytes))) {
                if (0 != length) {
                    System.out.print(new String(bytes, 0, length));
                }
            }
        }
    
    }
    
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题