读取NANOHTTPD的InputStream会产生Socket TimeOut异常

时间:2014-07-24 10:40:11

标签: inputstream bufferedreader bufferedinputstream nanohttpd

我正在尝试使用以下代码从IHTTPSession.getInputStream()读取InputStream,但每次都会给出Socket TimeOut异常。

private String readInStream(InputStream in){

        StringBuffer outBuffer=new StringBuffer();
        BufferedInputStream bis=new BufferedInputStream(in);
        try {
            while(bis.available()>0){
                int ch= bis.read();
                outBuffer.append((char)ch);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Log.e("DATA_Length", "outputBuffer :"+outBuffer.toString().length());
        return outBuffer.toString();
    }

我也尝试了以下方法,但出现了相同的异常

private String readInStream(InputStream in){
        String line="";
        StringBuffer outBuffer=new StringBuffer();

        BufferedReader rd=new BufferedReader(new InputStreamReader(in));

        try {
            while((line=rd.readLine()) != null){
                outBuffer.append(line);
            }
        } catch (IOException e) {
            Log.e("IOException", "IOException in readInStream:");
            e.printStackTrace();
        }

        Log.e("DATA_Length", "outputBuffer :"+outBuffer.toString().length());
        return outBuffer.toString();
    }

2 个答案:

答案 0 :(得分:5)

从标题中获取内容长度。阅读contentLength解决了问题。

答案 1 :(得分:0)

可以确认接受的答案有效(从标题中获取内容长度并进行阅读)。这是一些将InputStream变成String的示例代码:

try {
    int contentLength = Integer.valueOf(session.getHeaders().get("content-length"));
    String msg = new String(in.readNBytes(contentLength)); // the request body
} catch (IOException e) {
    e.printStackTrace();
}

如果您想在此处避免使用NullPointerException,请先将content-length标头解析为整数,然后检查其是否存在。