简体   繁体   中英

How to get an HTTPRequest from a Java Socket using Apache HttpComponents

My simple server has a ServerSocket object that listens on a port and accepts sockets.

Socket socket = serverSocket.accept();

Once I have this socket, how do I turn it into an HttpRequest object, so I can, for instance, easily determine the domain the socket is looking for?

A socket is on a completely different layer of the network stack than a http request. So you can't just "turn" a socket into a http-request. See http://en.wikipedia.org/wiki/OSI_model -> the socket operates at layer 4, a http-request would be on layer 7.

A socket is a tool to handle network communication. That does not necessarily have to be http, but can be anything (eg ftp, or a proprietary protocol). The socket will just give you a stream of data, you have to interpret.

I suggest, you use something like apache http-components ( http://hc.apache.org/ ) for the webserver-stuff. There are a lot of frameworks an libraries that do what you need, do not implement it yourself.

My friend, you will have to read data from the socket, parse it, and determine if it complies with http protocol, then create httprequest, which you can forward to whoever needs it. and this has already been done for you in servers such as jetty or tomcat

I've found a way that works:

    Socket serverSoc = srvSocket.accept();
    DefaultHttpServerConnection serverConn = null;
    try {
        HttpParams params = new BasicHttpParams();
        serverConn = new DefaultHttpServerConnection();
        serverConn.bind(serverSoc, params);
        HttpRequest request = serverConn.receiveRequestHeader();
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM