只要有一些东西(Android / Java),如何继续读取InputStream?

时间:2017-04-12 14:04:48

标签: java android inputstream

我使用REST API从硬件键盘获取输入。我想知道如果有输入,如何继续阅读InputStream,然后优雅地停止而不会抛出SocketTimoutException

我的代码

// Start a new thread for reading the keyboard input
new Thread(new Runnable() {
    @Override
    public void run() {

        InputStream inputStream = null;
        try {

            // Set byte stream from response body
            inputStream = response.body().byteStream();

            // I THINK THIS IS THE PROBLEM. WHILE (TRUE) //
            while (true) {

                // This is where the rest response is read into an array of bytes. I interpret this array below and it seems to work as intended.
                final byte[] buffer = new byte[256];
                int bytesRead = inputStream.read(buffer, 0, buffer.length);

                // This was more for debugging purposes... it never get invoked, as far as I can tell.
                if (bytesRead < 0) {
                    Log.w(TAG, "...Returning. 0 bytes read.");
                    return;
                }

                // I'll specify what a response looks like below this code block.
                String fullResponse = new String(buffer, StandardCharsets.UTF_8);
                Log.v(TAG, "...Full rest response : \n " + fullResponse);

                // This processes the response, narrowing down to just the keycode. This works as it's supposed to.
                processResponse(fullResponse);

            }

        } catch (IOException e) {
            e.printStackTrace();
            Log.v(TAG, "...Problem reading input stream");

        } finally {

            // Close input stream when I'm done with it.
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}).start();

所以这是我从其他api得到的响应的一个例子。我的processResponse()方法使用我按下的密钥代码(在本例中为34)查找并更新文本视图。这是按预期工作的。

...Full rest response : 

timeout: 2000000                                                              
event: keypress                                                                    
id: 1492005344                                                                      
data: {"device":"keyboard","pressedKeycodes":"34 "}

我想知道的是,只要有东西存在,如何继续阅读InputStream,并且在没有抛出SockoutTimeoutException之后不再接收输入后停止。如果我不这样做while(true)我没有得到例外,但它只能读取一个按键盘。

以下是例外:

04-12 15:18:02.467 7585-7810/com.accutime.restpractice W/System.err: java.net.SocketTimeoutException
04-12 15:18:02.469 7585-7810/com.accutime.restpractice W/System.err:     at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
04-12 15:18:02.470 7585-7810/com.accutime.restpractice W/System.err:     at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:37)
04-12 15:18:02.471 7585-7810/com.accutime.restpractice W/System.err:     at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:237)
04-12 15:18:02.472 7585-7810/com.accutime.restpractice W/System.err:     at okio.Okio$2.read(Okio.java:140)
04-12 15:18:02.473 7585-7810/com.accutime.restpractice W/System.err:     at okio.AsyncTimeout$2.read(AsyncTimeout.java:238)
04-12 15:18:02.474 7585-7810/com.accutime.restpractice W/System.err:     at okio.RealBufferedSource.request(RealBufferedSource.java:66)
04-12 15:18:02.475 7585-7810/com.accutime.restpractice W/System.err:     at okio.RealBufferedSource.require(RealBufferedSource.java:59)
04-12 15:18:02.476 7585-7810/com.accutime.restpractice W/System.err:     at okio.RealBufferedSource.readHexadecimalUnsignedLong(RealBufferedSource.java:284)
04-12 15:18:02.477 7585-7810/com.accutime.restpractice W/System.err:     at okhttp3.internal.http.Http1xStream$ChunkedSource.readChunkSize(Http1xStream.java:441)
04-12 15:18:02.478 7585-7810/com.accutime.restpractice W/System.err:     at okhttp3.internal.http.Http1xStream$ChunkedSource.read(Http1xStream.java:422)
04-12 15:18:02.479 7585-7810/com.accutime.restpractice W/System.err:     at okio.RealBufferedSource.read(RealBufferedSource.java:45)
04-12 15:18:02.479 7585-7810/com.accutime.restpractice W/System.err:     at okio.ForwardingSource.read(ForwardingSource.java:35)
04-12 15:18:02.480 7585-7810/com.accutime.restpractice W/System.err:     at retrofit2.OkHttpCall$ExceptionCatchingRequestBody$1.read(OkHttpCall.java:279)
04-12 15:18:02.481 7585-7810/com.accutime.restpractice W/System.err:     at okio.RealBufferedSource$1.read(RealBufferedSource.java:386)
04-12 15:18:02.482 7585-7810/com.accutime.restpractice W/System.err:     at com.accutime.restpractice.MainActivity$1$1.run(MainActivity.java:172)
04-12 15:18:02.483 7585-7810/com.accutime.restpractice W/System.err:     at java.lang.Thread.run(Thread.java:818)

2 个答案:

答案 0 :(得分:0)

首先,我将创建一个读取InputStream并返回byte[]内容读取的实用程序类。假设在此示例中,实用程序类称为InputOutputStreams

我的方法将是:

public static byte[] readFully(InputStream input) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[256];
    int totalBytesRead = 0;
    int bytesRead = 0;

    while (input.read(buffer) > 0) {
        baos.write(buffer, 0, bytesRead);
    }

    return baos.toByteArray();
}

然后我将删除您拥有的while循环(以及各种实现),并使用上面实现的实用程序类来检索InputStream的内容,如下所示:

    // Start a new thread for reading the keyboard input
            new Thread(new Runnable() {
                @Override
                public void run() {

                    InputStream inputStream = null;
                    try {

                        // Set byte stream from response body
                        inputStream = response.body().byteStream();

                            // I'll specify what a response looks like below this code block.
                            //THIS IS WHERE I USE THE UTILITY CLASS
                            String fullResponse = new String(InputOutputStreams.readFully(inputStream), StandardCharsets.UTF_8);
                            Log.v(TAG, "...Full rest response : \n " + fullResponse);

                            // This processes the response, narrowing down to just the keycode. This works as it's supposed to.
                            processResponse(fullResponse);

                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.v(TAG, "...Problem reading input stream");

                    } finally {

                        // Close input stream when I'm done with it.
                        if (inputStream != null) {
                            try {
                                inputStream.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }).start();

我希望这会有所帮助......

答案 1 :(得分:0)

我找到了解决问题的方法。问题正文中的代码可以保持不变,但是当我创建改造构建器时,我需要添加一个read timeoutwrite timeout max value的OkHttpClient。

这导致程序不会超时SocketNotFound异常,并且很快就会接受输入。

这是我的代码:

    // TODO 9 : Set a timeout for the connection // <- I NEEDED TO ADD THIS BLOCK ***
    OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
            .readTimeout(Integer.MAX_VALUE, TimeUnit.MILLISECONDS)
            .writeTimeout(Integer.MAX_VALUE, TimeUnit.MILLISECONDS)
            .build();

    // TODO 7 : Create retrofit builder
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(ClockAPI.ENDPOINT) // Refers to endpoint defined in GithubAPI
            .addConverterFactory(GsonConverterFactory.create(gson)) // Refers to gson builder, created
            .client(okHttpClient) // <- AND THIS LINE ***
            .build();

    // TODO 8 : Create REST API through retrofit builder
    clockUserAPI = retrofit.create(ClockAPI.class);