J’utilise Pattern
/ Matcher
pour obtenir le code de réponse dans une réponse HTTP. groupCount
renvoie 1, mais j’obtiens une exception en essayant de l’obtenir! Une idée pourquoi?
Voici le code:
//get response code Ssortingng firstHeader = reader.readLine(); Pattern responseCodePattern = Pattern.comstack("^HTTP/1\\.1 (\\d+) OK$"); System.out.println(firstHeader); System.out.println(responseCodePattern.matcher(firstHeader).matches()); System.out.println(responseCodePattern.matcher(firstHeader).groupCount()); System.out.println(responseCodePattern.matcher(firstHeader).group(0)); System.out.println(responseCodePattern.matcher(firstHeader).group(1)); responseCode = Integer.parseInt(responseCodePattern.matcher(firstHeader).group(1));
Et voici la sortie:
HTTP/1.1 200 OK true 1 Exception in thread "Thread-0" java.lang.IllegalStateException: No match found at java.util.regex.Matcher.group(Unknown Source) at cs236369.proxy.Response.(Response.java:27) at cs236369.proxy.ProxyServer.start(ProxyServer.java:71) at tests.Hw3Tests$1.run(Hw3Tests.java:29) at java.lang.Thread.run(Unknown Source)
pattern.matcher(input)
crée toujours un nouveau matcher, vous devrez donc rappeler les matches()
.
Essayer:
Matcher m = responseCodePattern.matcher(firstHeader); m.matches(); m.groupCount(); m.group(0); //must call matches() first ...
Vous écrasez constamment les correspondances obtenues en utilisant
System.out.println(responseCodePattern.matcher(firstHeader).matches()); System.out.println(responseCodePattern.matcher(firstHeader).groupCount());
Chaque ligne crée un nouvel object Matcher.
Tu devrais y aller
Matcher matcher = responseCodePattern.matcher(firstHeader); System.out.println(matcher.matches()); System.out.println(matcher.groupCount());