在Logcat中打印InputStream

在Logcat中打印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));

07-27 16:18