Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中对http请求使用writeUTF和readUTF_Java_Sockets_Networking - Fatal编程技术网

在Java中对http请求使用writeUTF和readUTF

在Java中对http请求使用writeUTF和readUTF,java,sockets,networking,Java,Sockets,Networking,这是一个Java方法,它尝试对指定的网页进行爬网。我使用writeUTF和readUTF与服务器进行套接字通信 static void get_html(String host, String page, int port) throws IOException { Socket sock = new Socket(host, port); String msg = MessageFormat.format("GET {0} HTTP/1.1\r\nHost: {

这是一个Java方法,它尝试对指定的网页进行爬网。我使用writeUTF和readUTF与服务器进行套接字通信

static void get_html(String host, String page, int port) throws IOException {
        Socket sock = new Socket(host, port);
        String msg = MessageFormat.format("GET {0} HTTP/1.1\r\nHost: {1}\r\n\r\n", page, host);

        DataOutputStream outToServer = new DataOutputStream(sock.getOutputStream());
        DataInputStream inFromServer = new DataInputStream(sock.getInputStream());

        InputStream stream = new ByteArrayInputStream(msg.getBytes(StandardCharsets.UTF_8));
        BufferedReader buf = new BufferedReader(new InputStreamReader(stream));
        String outMsg;

        while ((outMsg = buf.readLine()) != null) {
            System.out.println("Sending message: " + outMsg);
            outToServer.writeUTF(outMsg);

            String inMsg;
            try {
                inMsg = inFromServer.readUTF();
            } catch (EOFException eof) {
                break;
            }
            System.out.println(inMsg);
        }
        sock.close();
    }

我以这种方式编写它的原因是为了模拟
c
代码,其中有一个
send()
的while循环从缓冲区进行所有传递,还有一个
recv()
的while循环从缓冲区进行,直到它点击“null”。当执行我的代码时,它只是挂在那里,我怀疑这是由于在我发送完所有消息之前调用了readUTF。如果是这种情况,有什么办法可以解决吗?

你不能这样做。HTTP被定义为文本行
writeUTF()
不写入文本,它写入一种特殊格式,以16位二进制长度的字开始。类似地,HTTP服务器不会将该格式回复到您的
readUTF()
调用中。请参阅Javadoc

必须使用二进制流和
write()
方法,并使用
\r\n
作为行终止符。根据输出格式的不同,您可能无法使用
readLine()
。最好不要,那么您就不必编写两段代码:再次使用二进制流

事实上,您应该抛弃它,使用
HttpURLConnection
。实现HTTP并不像人们匆忙想象的那么简单