I'm trying to build an HTTP server, I searched the net to solve this problem, but I did not find anything like that.
I'm trying to customize an inputstream to fit read requests and HTTP responses directly from inputstream. The class, which implements an interface) that generates the null pointer exception is as follows (n = in.available ();
):
public class MyHTTPInputStream extends HTTPInputStream{
public InputStream in = null;
public String request, reply, dataIn; // dataIn:= data read from InputStream
public HTTPMyRequest myRequest;
public HTTPMyReply myReply;
public MyHTTPInputStream(InputStream is) {
super(is);
// TODO Auto-generated constructor stub
}
@Override
protected void setInputStream(InputStream is) {
// TODO Auto-generated method stub
// initialize the variable
this.in = is;
request = null;
reply = null;
dataIn = null;
}
@Override
public HTTPRequest readHttpRequest() throws HTTPProtocolException {
request = readFromStream(); // read from inputStream
System.out.println(request);
myRequest = new HTTPMyRequest(request);
return myRequest;
}
@Override
public HTTPReply readHttpReply() throws HTTPProtocolException {
reply = readFromStream(); // read from inputStream
myReply = new HTTPMyReply(reply);
return myReply;
}
@Override
public void close() throws IOException {
// TODO Auto-generated method stub
in.close();
}
public String readFromStream(){
// read data from InputStream to String
int n = 0;
try {
n = in.available(); // ******null pointer exception
System.out.println("n: "+n);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("n: "+n);
byte[] bytes = new byte[n];
try {
in.read(bytes, 0, n);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String req = new String(bytes, StandardCharsets.UTF_8);
System.out.println(req);
return req;
}
}
In the constructor super(is);
, refers to this in the interface:
public HTTPInputStream( InputStream is ) {
this.setInputStream(is);
}
This is part of my main class (testServer
) to call up the object:
...
/*
* TEST INPUTSTREAM
*/
System.out.println("_____HTTP Inputstream_____");
// read HTTP request from file request.txt
InputStream isReq = new FileInputStream(new File("src\\source\\request.txt"));
MyHTTPInputStream myIsReq = new MyHTTPInputStream(isReq);
HTTPMyRequest myRequest =(HTTPMyRequest) myIsReq.readHttpRequest();
System.out.println("_______Read request_______");
...
the file request.txt is in the src directory and is a simple string containing an http request, I also managed to print it on screen without problems in the main class, but in the class readFromStream()
it generates this exception(I hid the path with ...):
_____HTTP Inputstream_____
Exception in thread "main" java.lang.NullPointerException at ....MyHTTPInputStream.readFromStream(MyHTTPInputStream.java:59) at ....MyHTTPInputStream.readHttpRequest(MyHTTPInputStream.java:35) at ....testServer.main(testServer.java:88)