请求正文比客户端发送的短 - HttpServer Java

Request Body Shorter than Sent by Client - HttpServer Java

我使用 HttpServer 创建 Java 应用程序,如下所示:

public class Application 
{
public static void main(String args[])
{
    HttpServer httpPaymentServer;
    httpPaymentServer = HttpServer.create(new InetSocketAddress(Config.portPayment), 0);
    httpPaymentServer.createContext("/json", new Payment("json"));
}
public class Payment implements HttpHandler
{
    public Payment(String dataType)
    {
    }
    public void handle(HttpExchange httpExchange) throws IOException 
    { 
        String body = "";
        if(httpExchange.getRequestMethod().equalsIgnoreCase("POST")) 
        {
            try 
            {
                Headers requestHeaders = httpExchange.getRequestHeaders();
                Set<Map.Entry<String, List<String>>> entries = requestHeaders.entrySet();
                int contentLength = Integer.parseInt(requestHeaders.getFirst("Content-length"));
                InputStream inputStream = httpExchange.getRequestBody();
                byte[] postData = new byte[contentLength];
                int length = inputStream.read(postData, 0, contentLength);
                if(length < contentLength)
                {                   
                }
                else
                {
                    String fullBody = new String(postData);                 
                    Map<String, String> query = Utility.splitQuery(fullBody);
                    body = query.getOrDefault("data", "").toString();
                }
            } 
            catch (Exception e) 
            {
                e.printStackTrace(); 
            }    
        }
    }
}
}

在我的服务器(Centos 7)上,第一次请求,是没有问题的。但是在下一个请求中,并不是所有的请求体都可以被读取。 但是在我的 PC (Windows 10) 上没问题。 问题是什么。

对于您的 InputStream,您只调用 read 一次 - 它可能不会 return 所有数据。那时甚至可能没有收到该数据。

相反,您应该在循环中调用 read,直到获得所有字节(当您到达流 read returns -1 的末尾时)。或者使用此处建议的方法之一 How to read / convert an InputStream into a String in Java?

谢谢。这对我有用

public void handle(HttpExchange httpExchange) throws IOException 
{
    String body = "";
    if(httpExchange.getRequestMethod().equalsIgnoreCase("POST")) 
    {
        try 
        {
            Headers requestHeaders = httpExchange.getRequestHeaders();
            Set<Map.Entry<String, List<String>>> entries = requestHeaders.entrySet();
            int contentLength = Integer.parseInt(requestHeaders.getFirst("Content-length"));
            InputStream inputStream = httpExchange.getRequestBody();             
            int j;
            String fullBody = "";
            for(j = 0; j < contentLength; j++)
            {
                byte b = (byte) httpExchange.getRequestBody().read();
                fullBody += String.format("%c", b);
            }
            Map<String, String> query = Utility.splitQuery(fullBody);
            body = query.getOrDefault("data", "").toString();
        } 
        catch (Exception e) 
        {
            e.printStackTrace(); 
        }
    }
}