how to read body of a post packet in java
This question already has an answer here:
if you use Java 8 you can do
List<String> content = BR.lines().collect(Collectors.toList());
Otherwise you can do
List<String> content = new ArrayList<>();
String line;
while((line = BR.readLine()) != null) {
content.add(line);
}
Then parse/format as you wish to get the response as a whole.
BR.readLine()
only returns the first line; you need to loop through the BufferedReader
to read all lines. One possible way would be:
String fullMessage;
String aux;
do{
aux = BR.readLine();
fullMessage = fullMessage.concat(aux);
}while(aux != null);
This is just an example to illustrate the idea.
Read the documentation: https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine()
Example for 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);
For older versions of java you can use:
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);
EDIT: Sorry append is for StringBuffer and StringBuilder, my bad sorry.
EDIT2: Added 2 example with more information.
链接地址: http://www.djcxy.com/p/13740.html上一篇: 来自/ sys / fs / cgroup /在Java中的长度文件?
下一篇: 如何在java中阅读一个post包的正文