3

InputStreamをlogcatに出力したい(テスト用/後で使用します)。現在のコードは次のとおりです。

        @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

あなたTAGは次のような定数でなければなりません:

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

次に、次のようなことを行います。

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

eは印刷スタックからのエラーです。

また、Androidライブラリにログをインポートすることも確認してください。

また、コードを確認した後、httpConnection()try / catchステートメントで囲み、エラーをキャッチしてログファイルに入れることもできます。ストリームに何かがある場合、またはnullでない場合はログを印刷しますが、接続がないかどうかを知りたい場合は、null値が返されます。

お役に立てば幸いです。

于 2012-07-06T08:15:22.653 に答える
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 に答える