基本上我已经创建了一个读取传入数据包的java服务器,但问题是当一个post数据包到来时它没有读取包含实际数据的主体部分,它将消息显示为POST /index.html http/1.1
以下是我在服务器上阅读数据的方法:
try{
IR = new InputStreamReader(socket.getInputStream());
}catch(Exception ie){
System.out.println("Cound'nt create IR");
}
BufferedReader BR = new BufferedReader(IR);
String MESSAGE = null;
try{
MESSAGE = BR.readLine();
}catch(Exception ie){
System.out.println("Cound'nt Receive Message");
}
System.out.println(MESSAGE);
您能否告诉我如何阅读收到的信息包的正文?
答案 0 :(得分:1)
如果您使用Java 8,则可以执行
List<String> content = BR.lines().collect(Collectors.toList());
否则你可以做到
List<String> content = new ArrayList<>();
String line;
while((line = BR.readLine()) != null) {
content.add(line);
}
然后解析/格式化,以便作为整体获得响应。
答案 1 :(得分:0)
BR.readLine()
仅返回第一行;你需要遍历BufferedReader
来读取所有行。一种可能的方式是:
String fullMessage;
String aux;
do{
aux = BR.readLine();
fullMessage = fullMessage.concat(aux);
}while(aux != null);
这只是举例说明这个想法。
阅读文档:https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine()
java 7 +的示例
String message = null;
//Try with resources, java will handle the closing of the stream, event if exception is thrown.
try ( InputStreamReader inputStream = new InputStreamReader(socket.getInputStream());
BufferedReader bufferReader = new BufferedReader(inputStream);) {
String aux = null;
do {
aux = bufferReader.readLine();
message = message.concat(aux);
} while (aux != null);
} catch (IOException e) {
System.out.println("Failed to read input stream from socket");
}
System.out.println("Message: " + message);
对于旧版本的java,您可以使用:
InputStreamReader inputStream = null;
BufferedReader bufferReader = null;
String message = null;
try {
inputStream = new InputStreamReader(socket.getInputStream());
bufferReader = new BufferedReader(inputStream);
String aux = null;
do {
aux = bufferReader.readLine();
message = message.concat(aux);
} while (aux != null);
inputStream.close();
bufferReader.close();
} catch (IOException e) {
//Read throws IOException, don't just use Exception (this could hide other exceptions that you are not treating).
System.out.println("Failed to read input stream from socket");
} finally{
//Use 2 try-catch, if you only use one and the first fails, the second will never close.
try{inputStream.close();}catch(IOException ioe){}
try{bufferReader.close();}catch(IOException ioe){}
}
System.out.println("Message: "+message);
编辑:抱歉追加是针对StringBuffer和StringBuilder的,不好意思。
EDIT2:添加了2个包含更多信息的示例。