How to parse first line of HTTP Get Request in java?

时间:2016-02-03 03:05:29

标签: java http

I was wondering if there is a quick way to parse the first line of a HTTP get request to just grab the directory information? For example, if I have: GET /test.txt HTTP/1.1, what would be the easiest way to get just test.txt or whatever the request might be. The file might change so hard coding is out.

Is string.split() the easiest way. If so what would the best way to split it be. I can't split it by "/", because there could be more than one I need. Is it possible to just split it an grab everything after the first "/" and then stop at the first space. Thanks.

EDIT:

Would it be better to just remove GET and HTTP/1.1 since I won't need them, and then just grab everything else?

2 个答案:

答案 0 :(得分:0)

3.1.1. Request Line

A request-line begins with a method token, followed by a single space (SP), the request-target, another single space (SP), the protocol version, and ends with CRLF.

 request-line   = method SP request-target SP HTTP-version CRLF

Source: http://tools.ietf.org/html/rfc7230

Your method is fine. Just remove Method and HTTP-Version:

String requestUri = firstLineStr.substring(firstLineStr.indexOf(' ')+1, firstLineStr.lastIndexOf(' '));

答案 1 :(得分:0)

Would it be better to just remove GET and HTTP/1.1 since I won't need them, and then just grab everything else? -> if you are sure that the file name is the only thing that you need and will always be available between GET and HTTP/1.1 then yes, it is the right way among all the possible solutions. But if you are working on some web application then I believe there are APIs available to retrieve the information. Also make sure that your request is always GET else you have to keep the options available for PUT and etc