Http监听器仅适用于POST而不是GET

时间:2011-05-27 09:20:11

标签: java http post get

我有一个简单的程序,服务器或客户端不确定它是哪一端。我打开一个端口并接受它上面的消息。这工作但昨晚我通过GET而不是POST恢复了一条消息时崩溃了。你可能已经注意到我对网络很陌生。

我收到传输正常(套接字的东西),但我无法阅读该消息。

这是我目前使用的代码。

//read HTTp header until the message size comes in
            for(int eight = 0; eight < 8; eight++)
            {
                message = in.readLine();
                LOGGER.fatal(eight);
                LOGGER.fatal(message);

                if(message.contains("Content-Length"))
                {
                    try {

                        Pattern pattern = Pattern.compile("\\d+");
                        Matcher matcher = pattern.matcher(message);
                        while (matcher.find()) {
                            sizeInt = Integer.parseInt(matcher.group());
                                               }
                        }

                    catch (Exception e) 
                        {
                            LOGGER.fatal("size not found on header line", e);
                            //System.exit(-1);
                        }                   
                }
            }

            LOGGER.fatal(sizeInt);

            LOGGER.fatal("---------------------------");

            char[] buffer =new char[sizeInt];

            //skip blank line between header and message
            message = in.readLine();

            //read message
            int fullRead = 0;
            int thisRead = 0;
            do
            {
                thisRead = in.read(buffer, fullRead, sizeInt - fullRead);   
                LOGGER.info(fullRead + " of " + sizeInt + " bytes of message read");
                fullRead += thisRead;

            }while(fullRead != sizeInt);

我遇到的问题是GET方法没有看到以字节为单位的消息大小,没有它我不知道如何在没有它的情况下读取消息。

我正在使用java。

任何人都可以建议我如何编辑此代码以理解GET消息。

3 个答案:

答案 0 :(得分:1)

GET请求没有任何内容 - 没有什么可读的。任何数据都必须位于标题/网址中。

答案 1 :(得分:1)

看起来你想要实现一个HTTP服务器(它不是客户端,因为你想要读取HTTP请求,而不是制作它们)。如果你是“非常新的网络”,我不会推荐它。无论如何,如果你真的想要构建自己的HTTP服务器,那么Web上有一些例子,例如this one。另一种方法是,如果您的应用程序中需要HTTP服务器,则使用com.sun.net.httpserver.HttpServer(该链接包含一个最小示例)。

答案 2 :(得分:0)

HTTP GET没有任何内容,因此没有内容长度。此外,HTTP POST不一定需要在HTTP / 1.1中指定Content-Length:HTTP Message Length

相关问题