如何在java中阅读一个post包的正文

这个问题在这里已经有了答案:

  • 将InputStream读取/转换为字符串56个答案

  • 如果你使用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);
    }
    

    然后解析/格式化,因为您希望整体获得响应。


    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,我很抱歉。

    编辑2:增加了2个更多信息的例子。

    链接地址: http://www.djcxy.com/p/13739.html

    上一篇: how to read body of a post packet in java

    下一篇: Decoding InputStream for Java HTTP GET