3

我想在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;
        }

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

4

3 回答 3

14
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));
于 2012-07-06T08:21:32.327 回答
0
Just add this code to if(in != null):   

    byte[] reqBuffer = new byte[1024];
    int reqLen = 1024;
    int read = -1;

    StringBuilder result = new StringBuilder();
    try {
        while ((read = is.read(reqBuffer, 0, reqLen)) >= 0)
            result.append(new String(reqBuffer, 0, read));
    } catch (IOException e) {
        e.printStackTrace();
    } 


Log.d("TAG", result.toString());
于 2012-07-06T08:17:43.090 回答
0

TAG应该是一个常数,如:

public final String TAG = YourActivity.class.getSimpleName();

然后你会做类似的事情:

Log.e(TAG, "You're message here:", e)

e 是来自打印堆栈的错误。

您还需要确保将 Log 导入 Android 库中。

此外,在查看您的代码之后,您可能希望httpConnection()用 try/catch 语句包围您的语句,这样您就可以捕获错误并将其放入您的日志文件中。如果您的流有某些内容或不为空,您将打印日志,但您想知道是否没有连接,这会给您一个空值。

希望有帮助。

于 2012-07-06T08:15:22.653 回答