11package client ;
22
3+ import exception .InvalidCommandException ;
34import message .consts .WebMethods ;
5+ import util .ArgIterator ;
46
57import java .net .URI ;
68import java .util .ArrayList ;
@@ -21,7 +23,7 @@ public class ClientDriver {
2123 The default value of the port number is 80.
2224 Only support HTTP protocol (not HTTPS).
2325
24- OPTIONS
26+ OPTIONS
2527 -m <METHOD> Send with the specified web method.
2628 Only supports GET and POST.
2729 The default value is GET.
@@ -35,55 +37,9 @@ Only support HTTP protocol (not HTTPS).
3537 e.g.: User-Agent:AbaAba/0.1
3638 """ ;
3739
38- private static class InvalidCommandException extends Exception {
39- public InvalidCommandException (String message ) {
40- super (message );
41- }
42- }
43-
44- private static class ArgIterator {
45- private final
46- String [] args ;
47- private
48- int idx ;
49-
50- public ArgIterator (String [] args ) {
51- this .args = args ;
52- this .idx = 0 ;
53- for (String first ; (first = peek ()) != null && !first .startsWith ("http://" ); )
54- next ();
55-
56- }
57-
58- public boolean hasNext () {
59- return idx < args .length ;
60- }
61-
62- public String peek () {
63- if (hasNext ())
64- return args [idx ];
65- else
66- return null ;
67- }
68-
69- public String next () {
70- if (hasNext ())
71- return args [idx ++];
72- else
73- return null ;
74- }
75-
76- public String [] nextValues () {
77- ArrayList <String > as = new ArrayList <>();
78- for (String token ; (token = peek ()) != null && !token .startsWith ("-" ); next ())
79- as .add (token );
80- return as .toArray (new String [0 ]);
81- }
82- }
83-
8440 public static void main (String [] args ) {
8541 try {
86- ArgIterator ai = new ArgIterator (args );
42+ ArgIterator ai = new ArgIterator (args , "http://" );
8743
8844 String raw = ai .next ();
8945 if (raw == null || raw .startsWith ("-" ))
@@ -92,12 +48,8 @@ public static void main(String[] args) {
9248 URI u = new URI (raw );
9349
9450 String hostName = u .getHost ();
95- String query = u .getQuery ();
9651 int port = u .getPort ();
97- String path = u .getPath ();
98-
9952 if (port == -1 ) port = 80 ;
100- if (path == null || path .length () == 0 ) path = "/" ;
10153
10254 String method = WebMethods .GET ;
10355 boolean keepAlive = false ;
@@ -116,21 +68,13 @@ public static void main(String[] args) {
11668 || WebMethods .POST .equals (method );
11769 }
11870
119- case "--keep-alive" -> {
120- keepAlive = true ;
121- }
71+ case "--keep-alive" -> keepAlive = true ;
12272
123- case "-b" -> {
124- body = ai .next ();
125- }
73+ case "-b" -> body = ai .next ();
12674
127- case "-h" -> {
128- headers = ai .nextValues ();
129- }
75+ case "-h" -> headers = ai .nextValues ();
13076
131- default -> {
132- throw new InvalidCommandException ("Invalid token at \" %s\" " .formatted (opt ));
133- }
77+ default -> throw new InvalidCommandException ("Invalid token at \" %s\" " .formatted (opt ));
13478 }
13579 }
13680
0 commit comments