reader.readLine())返回null但是打印内容

时间:2015-04-10 21:40:57

标签: android web web-scraping

我想获得服务器响应(实际上是来自网站的文本),即使它正在返回null但是正在打印内容。 代码:

        inputStream = connection.getInputStream();
        String response = "Test";
        Log.i("String Content", response);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        while ((response = reader.readLine()) != null){
            Log.i("String Content", response);
            Log.i("Server Response", reader.readLine());
        }
        Log.i("String Content", response);

输出:

04-10 17:55:05.128    3404-3425/com.example.example I/String Content﹕ Test
04-10 17:55:05.129    3404-3425/com.chatter.chatter I/String Content﹕ [ 04-10 17:55:05.129  3404: 3425 I/Server Response ] Successfull!
04-10 17:55:05.129    3404-3425/com.example.example E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-279
    Process: com.example.example, PID: 3404
    java.lang.NullPointerException: println needs a message
            at android.util.Log.println_native(Native Method)

怎么可能?有人能帮帮我吗?。

1 个答案:

答案 0 :(得分:0)

如果你有一个InputStream并希望将其内容保存到String,你应该这样:

try{
    inputStream = connection.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream , StandardCharsets.UTF_8));
    String str = null;
    StringBuilder sb = new StringBuilder();
    while ((str = reader.readLine()) != null) {
        sb.append(str);
    }
    String response = sb.build();
    Log.d("String Content", response);
} catch (IOException e) {
    e.printStackTrace();
}