Reading InputStream of NANOHTTPD gives Socket TimeOut Exception
Asked Answered
I

2

7

I am trying to read the InputStream from IHTTPSession.getInputStream() using the following code but its gives Socket TimeOut Exception every time.

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();
    }

i also tried the following Method but the same exception arises

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();
    }
Icono answered 24/7, 2014 at 10:40 Comment(0)
I
7

Getting the content length from the header and reading up to it solved the problem.

Icono answered 14/8, 2014 at 11:13 Comment(0)
K
2

Can confirm the accepted answer works (getting content length from the header and reading up to it). Here is some example code to turn the InputStream into a 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();
}

If you want to prevent a NullPointerException here, check whether the content-length header actually exists before parsing it to an integer.

Kirstinkirstyn answered 27/9, 2019 at 12:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.