6

我用 Java 编写了一个 HTTP 服务器,用Poco编写了一个 C++ 客户端。这是 C++ 客户端代码的一部分:

URI uri("http://127.0.0.1:4444");
HTTPClientSession session(uri.getHost(), uri.getPort());

HTTPRequest req(HTTPRequest::HTTP_POST,
                "/pages/page",
                HTTPMessage::HTTP_1_1);

session.sendRequest(req);
HTTPResponse res;
std::istream &is = session.receiveResponse(res);

在最后一行中,我收到以下错误:

terminate called after throwing an instance of 'Poco::Net::NoMessageException'
  what():  No message received

但我不明白为什么。连接建立成功,请求的页面存在。我在已知网站(如维基百科)上尝试了相同的代码,它毫无例外地工作。

我还尝试在命令行中使用cURL (对我的服务器)发出完全相同的请求,它显示了服务器的响应,因此服务器看起来很好。

这是服务器以字符串形式的原始响应:

"HTTP/1.1 200 OK\r\n" +
"Server: [server name]\r\n" +
"Content-Type: text/xml; charset=utf-8\r\n" +
"Content-Length:" + bodyBytes.length + "\r\n" +
"Resource: " + job.resId + "\r\n\r\n" + 
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><JobRequest><InputRepresentation id=\"0\"/>    <effectsList><cvtColor><code> CV_RGB2GRAY </code></cvtColor><resize><scaleFactorX> 0.5 </scaleFactorX><scaleFactorY> 0.5 </scaleFactorY><interpolation> INTER_LINEAR </interpolation></resize><GaussianBlur><kSize> 3 </kSize><sigmaX> 2 </sigmaX><sigmaY> 2 </sigmaY><borderType> BORDER_REPLICATE </borderType></GaussianBlur></effectsList></JobRequest>"

我编写了一个简单的 HTTP 服务器,它对每个请求都有一个固定的响应,以测试出了什么问题。这是代码:

public class Test {
    public static void main(String[] args) {    
        try {
            ServerSocket serverSocket = new ServerSocket(4449);
            Socket clientSocket = serverSocket.accept();

            String body = "ab";
            byte[] bodyBytes = body.getBytes("UTF-8");

            String headers = "HTTP/1.1 200 OK\r\n" + 
                             "Server: Foo\r\n" +
                             "Content-Type: text/plain\r\n" +
                             "Content-Length: " + bodyBytes.length + "\r\n\r\n";

            byte[] headerBytes = headers.getBytes("UTF-8");

            byte[] responseBytes = new byte[headerBytes.length + bodyBytes.length];

            /* Fill responseBytes with the header and body bytes */
            int i = 0;
            for (int j = 0; j < headerBytes.length; ++j) {
                responseBytes[i] = headerBytes[j];
                ++i;
            }
            for (int j = 0; j < bodyBytes.length; ++j) {
                responseBytes[i] = bodyBytes[j];
                ++i;
            }
            clientSocket.getOutputStream().write(responseBytes);

        } catch (IOException e) {}
    }
}

即使使用此服务器,我也会遇到相同的异常。那么这里有什么问题呢?

4

2 回答 2

2

根据实验,我发现Content-Length如果您发出一个空的 POST 请求,则必须包含一个标头。IE,

req.add("Content-Length", "0");
于 2015-11-23T19:03:49.780 回答
0

我必须在我的处理程序代码中使用以下序列才能接收到最小的响应而不会出现No message received错误:

resp.setStatus( Poco::Net::HTTPResponse::HTTP_OK );
resp.setContentType( "text/json" );
ostream &out = resp.send();
out << "[]";
out.flush();
于 2018-08-14T01:53:49.270 回答