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

时间:2018-09-16 14:31:28

标签: java httpserver

我使用以下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)上没有问题。 问题是什么。

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

谢谢。这对我有用

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(); 
        }
    }
}