请求正文短于客户端发送的请求正文 - 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- 它可能不会返回所有数据。当时甚至可能没有收到这些数据。

相反,您应该在循环中调用read,直到获得所有字节(当您到达流的末尾时read返回 -1(。或者使用此处建议的方法之一 如何在 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(); 
}
}
}

最新更新