Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading InputStream of NANOHTTPD gives Socket TimeOut Exception

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();
    }
like image 970
Manas Pratim Chamuah Avatar asked Jul 24 '14 10:07

Manas Pratim Chamuah


2 Answers

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

like image 65
Manas Pratim Chamuah Avatar answered Nov 01 '22 06:11

Manas Pratim Chamuah


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.

like image 23
Skere Avatar answered Nov 01 '22 08:11

Skere