Reputation: 77
I have this line of strings:
String line = "GET /MyFile.extension HTTP/1.1\n\n"
I want to get only the the file name MyFile.extension string, I tried this but the problem the HTTP version could change.
String fileName = line.replace("GET /", "");
fileName = fileName.replace(" HTTP/1.1", "");
This doesn't work too:
string fileName = line.indexOf("MyFile.extension");
I don't know the file Name too, it could be any file, It there a way to get that file between the strings "GET/" and "HTTP/"?
Upvotes: 1
Views: 514
Reputation: 4909
public static void main(String []args)
{
String line = "GET /MyFile.extension HTTP/1.1\n\n";
// To find the index of "/"
int start = line.indexOf("/");
// To find the index of space from int start which I got from the line above
int end = line.indexOf(" ", start);
// To extract the given string from the start+1 index to the end index
String s = line.substring(start+1, end);
System.out.println(s);
}
Output :
MyFile.extension
Upvotes: 1
Reputation: 563
You could use regular expression to get you in the inner value
Pattern p = Pattern.compile("GET (.*?) HTTP/1.1")
Matcher m = p.matcher(s);
if (m.find()) {
System.out.println(m.group(1)); // MyFile.extension
}
Upvotes: 0
Reputation: 9648
You can simple do this: line.split(" ")[1].substring(1)
Here is the code snippet:
public static void main (String[] args)
{
String line = "GET /MyFile.extension HTTP/1.1\n\n";
System.out.println(line.split(" ")[1].substring(1));
}
Output:
MyFile.extension
Upvotes: 1