android - 在 Logcat 中打印 InputStream

标签 android inputstream

我想在logcat中打印InputStream(用于测试/稍后我会用到它),我目前的代码如下。

        @Override
        protected Void doInBackground(Void... params) {

            try {

                InputStream in = null;
                int response = -1;

                URL url = new URL(
                        "http://any-website.com/search/users/sports+persons");
                URLConnection conn = null;
                HttpURLConnection httpConn = null;
                conn = url.openConnection();

                if (!(conn instanceof HttpURLConnection))
                    throw new IOException("Not an HTTP connection");

                httpConn = (HttpURLConnection) conn;
                httpConn.setAllowUserInteraction(false);
                httpConn.setInstanceFollowRedirects(true);
                httpConn.setRequestMethod("GET");
                httpConn.connect();

                response = httpConn.getResponseCode();
                if (response == HttpURLConnection.HTTP_OK) {
                    in = httpConn.getInputStream();
                }

                if (in != null) {
                    Log.e(TAG, ">>>>>PRINTING<<<<<");
                    Log.e(TAG, in.toString());
                   // TODO: print 'in' from here
                }
                in.close();
                in = null;



            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

但我无法做到这一点,所以请检查代码并添加/修改代码以执行此操作。

最佳答案

String convertStreamToString(java.io.InputStream is) {
    try {
        return new java.util.Scanner(is).useDelimiter("\\A").next();
    } catch (java.util.NoSuchElementException e) {
        return "";
    }
}

在你的代码中:

                Log.e(TAG, ">>>>>PRINTING<<<<<");
                Log.e(TAG, in.toString());
                Log.e(TAG, convertStreamToString(in));

关于android - 在 Logcat 中打印 InputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11358277/

相关文章:

android - 需要帮助来创建布局

android - 在 Android 流中使用 flush() close() 的好处?

java - 为什么 java Scanner 没有读取所有行?

java - 我无法使用 getClassLoader 方法加载图像

java - 带有俄语网址的 ImageView

PHP 尝试插入数据库 GET 方法时出错

android - 如何停止动画(来自 ObjectAnimator)

安卓 AsyncHttpClient : how to POST a custom Object(model)?

java - 如何使用 FileInputStream 访问 jar 中的 txt 文件?

java - 在 InputStream#close() 上使用 finally 关键字