Extracting values ββfrom a string containing an HTTP header
I am looking for the best way to extract data from a String that contains an HTTP header. For example, I would like to get the number 160 from the content length portion of the string: "Content-Length: 160 \ r \ n".
It seems that all data in the HTTP header is preceded by a name, colon, and space, and the value is immediately followed by the characters '\ r' and '\ n'.
At the moment I am doing this:
int contentLengthIndex = serverHeader.lastIndexOf("Content-Length: ");
int contentLastIndex = serverHeader.length()-1;
String contentText = serverHeader.substring(contentLengthIndex + 16, contentLastIndex);
contentText = contentText.replaceAll("(\\r|\\n)", "");
int contentLength = Integer.parseInt(contentText);
But it seems like a mess and it is only useful for getting the "Content-Length" at the end of a line. Is there a more generic solution for extracting values ββfrom a string containing an HTTP header that can be configured to work for both int and String values?
I should also mention that the connection has to return data back to the browser upon request, which in my opinion prevents me from taking advantage of using HttpURLConnection.
A quick solution would be:
new Scanner(serverHeader).useDelimiter("[^\\d]+").nextInt());
Another way if you want to create Hashtable
headers:
String[] fields = serverHeader.trim().split(":");
String key = fields[0].trim();
String value = fields[1].trim();
I'm not sure why you are doing this tutorial, there is already an API for that!
use java.net.HttpURLConnection class
edited: also methods URLConnection.getContentLength () and URLConnection.getContentLengthLong ()
Have you tried to just remove all non-numeric characters from the string?
serverHeader = serverHeader.replaceAll("[^\\d.]", "");
If you are using a class Socket
to read data HTTP
, I suggest you use HttpURLConnection
it as it provides a convenient method for parsing Header Fields
.
It has a method public Map getHeaderFields()
that you can use to get all fields.
If you'd like to get started using the guide HttpURLConnection
, you can see it here .