forked from pquiring/javaforce
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHTTP.java
More file actions
679 lines (619 loc) · 17.7 KB
/
Copy pathHTTP.java
File metadata and controls
679 lines (619 loc) · 17.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
package javaforce;
/** HTTP Client
*
* @author pquiring
*/
import java.net.*;
import java.io.*;
import java.util.*;
public class HTTP {
protected Socket s;
protected OutputStream os;
protected InputStream is;
protected String host;
protected int port;
private Parameters request_headers = new Parameters();
private Parameters reply_headers = new Parameters();
private int code = -1;
public static boolean debug = false;
private Progress progress;
private static int timeout = 30000;
public static final String formType = "application/x-www-form-urlencoded";
private final static int bufsiz = 1024;
public static class Parameters {
private HashMap<String, String> params = new HashMap<>();
public String get(String name) {
return params.get(name);
}
public void put(String name, String value) {
params.put(name, value);
}
public String[] keys() {
return params.keySet().toArray(JF.StringArrayType);
}
public void clear() {
params.clear();
}
public HashMap<String, String> getHashMap() {
return params;
}
public static Parameters decode(String[] headers, int offset) {
Parameters p = new Parameters();
for(int i=offset;i<headers.length;i++) {
String ln = headers[i];
int idx = ln.indexOf(":");
if (idx == -1) continue;
String key = ln.substring(0, idx).trim();
String value = ln.substring(idx + 1).trim();
p.put(key, value);
}
return p;
}
public static Parameters decode(String[] headers) {
for(int i=0;i<headers.length;i++) {
if (headers[i].length() == 0) return decode(headers, i + 1);
}
return null;
}
}
/** Progress Listener */
public static interface Progress {
/** Invoked to update download progress.
* @param downloaded = progress so far
* @param length = total length (-1 = unknown)
*/
public void progress(long downloaded, long length);
}
protected static class Buffer {
public byte[] buf;
public int pos;
public int count;
public Buffer() {
buf = new byte[bufsiz];
pos = 0;
count = 0;
}
public void expand() {
byte[] newbuf = new byte[buf.length << 1];
if (count > 0) {
System.arraycopy(buf, pos, newbuf, 0, count);
}
buf = newbuf;
pos = 0;
}
public void condense() {
if (pos == 0) return;
if (count == 0) {
pos = 0;
return;
}
System.arraycopy(buf, pos, buf, 0, count);
pos = 0;
}
public void consume(int length) {
if (length > count) {
JFLog.log("HTTP:Error:Buffer.consume(length > count)");
}
pos += length;
count -= length;
if (count == 0) {
pos = 0;
}
}
public void consumeAll() {
pos = 0;
count = 0;
}
public void setLength(int length) {
if (buf.length == length) return;
byte[] newbuf = new byte[length];
if (buf.length > length) {
//copy part
System.arraycopy(buf, pos, newbuf, 0, length);
} else {
//copy all
System.arraycopy(buf, pos, newbuf, 0, count);
}
buf = newbuf;
pos = 0;
}
public void append(Buffer other) {
if (other.count == 0) return;
while (buf.length < count + other.count) {
expand();
}
if (pos > 0) condense();
System.arraycopy(other.buf, other.pos, buf, pos + count, other.count);
count += other.count;
other.consumeAll();
}
public void append(Buffer other, int maxCopy) {
if (other.count == 0) return;
if (maxCopy == 0) return;
int toCopy = maxCopy;
if (other.count < maxCopy) toCopy = other.count;
while (buf.length < count + toCopy) {
expand();
}
if (pos > 0) condense();
System.arraycopy(other.buf, other.pos, buf, pos + count, toCopy);
count += toCopy;
other.consume(toCopy);
}
public byte[] toArray() {
if (count != buf.length) {
return Arrays.copyOfRange(buf, pos, pos + count);
}
return buf;
}
}
/** Removes user info from HTTP URL. */
public static String cleanURL(String url) {
return JF.cleanURL(url);
}
public static String getUserInfo(String urlstr) {
try {
return new URI(urlstr).toURL().getUserInfo();
} catch (Exception e) {
return null;
}
}
public static String getHost(String urlstr) {
try {
return new URI(urlstr).toURL().getHost();
} catch (Exception e) {
return null;
}
}
public static int getPort(String urlstr) {
try {
return new URI(urlstr).toURL().getPort();
} catch (Exception e) {
return 80;
}
}
/** Set connect/read timeout in ms (default = 30000) */
public static void setTimeout(int timeout) {
HTTP.timeout = timeout;
}
public boolean open(String host) {
return open(host, 80);
}
public boolean open(String host, int port) {
this.host = host;
this.port = port;
try {
if (debug) JFLog.log("HTTP.connect:" + host + ":" + port);
s = new Socket();
s.connect(new InetSocketAddress(host, port), timeout);
s.setSoTimeout(timeout);
os = s.getOutputStream();
is = s.getInputStream();
} catch (Exception e) {
JFLog.log(e);
if (s != null) {
try {s.close();} catch (Exception e2) {}
s = null;
}
s = null;
return false;
}
return true;
}
/** Close connection. */
public void close() {
if (s != null) {
try {
s.close();
} catch (Exception e) {
JFLog.log(e);
}
s = null;
}
}
/** Returns connection status. */
public boolean isConnected() {
return s != null;
}
/** Registers a download progress listener. */
public void setProgressListener(Progress progress) {
this.progress = progress;
}
/** Set a request header. */
public void setHeader(String key, String value) {
request_headers.put(key, value);
}
/** Clears all request headers. */
public void clearHeaders() {
request_headers.clear();
}
/** Returns reply header. */
public String getHeader(String key) {
return reply_headers.get(key);
}
/** Returns reply headers. */
public HashMap<String, String> getHeaders() {
return reply_headers.getHashMap();
}
/** Returns last status code. */
public int getCode() {
return code;
}
private int read(Buffer buf, int length) throws Exception {
if (buf.count >= length) return length;
int maxlength = buf.buf.length - buf.pos - buf.count;
if (length > maxlength) {
if (buf.pos > 0) {
buf.condense();
maxlength = buf.buf.length - buf.count;
}
}
if (length > maxlength) {
length = maxlength;
if (length == 0) {
JFLog.log("HTTP:Error:buffer full:" + buf.buf.length + "," + buf.pos + "," + buf.count);
return 0;
}
}
int read = is.read(buf.buf, buf.pos + buf.count, length);
if (read > 0) {
buf.count += read;
}
return read;
}
private void write(byte[] data) throws Exception {
os.write(data);
}
private void sendRequest(String req) throws Exception {
write(req.getBytes("UTF-8"));
}
private void sendData(byte[] data) throws Exception {
write(data);
}
private boolean endOfHeaders(Buffer buf) {
if (buf.count < 4) return false;
int length = buf.count;
return ((buf.buf[length-4] == '\r') && (buf.buf[length-3] == '\n') && (buf.buf[length-2] == '\r') && (buf.buf[length-1] == '\n'));
}
private boolean haveChunkLength(Buffer buf) {
if (buf.count < 2) return false;
int length = buf.count;
int start = buf.pos;
int end = buf.pos + length - 1;
for(int pos=start;pos<end;pos++) {
if (buf.buf[pos] == '\r' && buf.buf[pos + 1] == '\n') return true;
}
return false;
}
private int getChunkLength(Buffer buf) {
int value = 0;
while (buf.buf[buf.pos] != '\r') {
value *= 16;
char digit = (char)buf.buf[buf.pos];
if ((digit >= '0') && (digit <= '9')) {
value += (digit - '0');
} else if ((digit >= 'A' && digit <= 'F')) {
value += (digit - 'A' + 10);
} else if ((digit >= 'a' && digit <= 'f')) {
value += (digit - 'a' + 10);
} else {
JFLog.log("HTTP:Error:Invalid chunk length");
return -1;
}
buf.consume(1);
}
buf.consume(2); //consume \r\n
return value;
}
private boolean getReply(OutputStream os) throws Exception {
Buffer buf = new Buffer();
Buffer req = new Buffer();
//read headers
reply_headers.clear();
do {
int read = read(buf, bufsiz);
buf.pos = 0;
buf.count = read;
while (buf.count > 0) {
if (req.count == req.buf.length) {
req.expand();
}
req.buf[req.count++] = buf.buf[buf.pos++];
buf.count--;
read--;
if (endOfHeaders(req)) break;
}
} while (!endOfHeaders(req));
//parse headers
long length = -1;
boolean chunked = false;
String[] lns = new String(req.toArray()).split("\r\n");
for(int i=1;i<lns.length;i++) {
String ln = lns[i];
int idx = ln.indexOf(':');
if (idx == -1) continue;
String key = ln.substring(0, idx).trim();
String value = ln.substring(idx+1).trim();
reply_headers.put(key, value);
if (debug) System.out.println("Reply:" + key + "=" + value);
switch (key.toLowerCase()) {
case "content-length": length = Long.valueOf(value); break;
case "transfer-encoding": chunked = value.contains("chunked"); break;
}
}
//parse reply : HTTP/1.x code msg
String reply = lns[0];
if (debug) System.out.println("Reply=" + reply);
int i1 = reply.indexOf(' ');
if (i1 == -1) {
JFLog.log("HTTP:Error:Invalid Reply");
return false;
}
int i2 = reply.substring(i1+1).indexOf(' ');
if (i2 == -1) {
JFLog.log("HTTP:Error:Invalid Reply");
return false;
}
code = Integer.valueOf(reply.substring(i1+1, i1+i2+1));
boolean disconn = reply.endsWith("1.0");
if (length == 0) {
if (disconn) close();
return true;
}
long copied = 0;
//read data
if (chunked) {
if (debug) System.out.println("HTTP:Reading Chunked reply");
//read chunked data
while (true) {
if (haveChunkLength(buf)) {
int chunkLength = getChunkLength(buf);
boolean endOfChunks = chunkLength == 0;
//read chunk
if (buf.count > 0) {
int toCopy = buf.count;
if (toCopy > chunkLength) toCopy = chunkLength;
os.write(buf.buf, buf.pos, toCopy);
chunkLength -= toCopy;
buf.consume(toCopy);
copied += toCopy;
}
while (chunkLength > 0) {
int toread = chunkLength;
if (toread > bufsiz) toread = bufsiz;
int read = read(buf, toread);
if (read > 0) {
copied += read;
if (progress != null) {
progress.progress(copied, -1);
}
os.write(buf.buf, buf.pos, read);
chunkLength -= read;
buf.consume(read);
}
}
//read \r\n
while (buf.count < 2) {
read(buf, 2 - buf.count);
}
buf.consume(2);
if (endOfChunks) {
if (disconn) close();
return true;
}
} else {
read(buf, bufsiz);
}
}
} else if (length != -1) {
if (debug) System.out.println("HTTP:Reading Length:" + length);
//read length data
if (buf.count > 0) {
copied += buf.count;
os.write(buf.toArray());
buf.consumeAll();
}
while (copied < length) {
int toread = bufsiz;
if (toread > length) {
toread = (int)length;
}
int read = read(buf, toread);
if (read > 0) {
copied += read;
if (progress != null) {
progress.progress(copied, length);
}
os.write(buf.toArray());
buf.consume(read);
}
}
if (disconn) close();
return true;
} else {
if (debug) System.out.println("HTTP:Reading till carrier dropped");
//read till carrier is dropped
do {
if (buf.count > 0) {
copied += buf.count;
if (progress != null) {
progress.progress(copied, -1);
}
os.write(buf.toArray());
buf.consumeAll();
}
} while (read(buf, bufsiz) >= 0);
if (disconn) close();
return true;
}
}
/** Append user headers. */
private void appendHeaders(StringBuilder req) {
String[] keys = request_headers.keys();
for(String key : keys) {
String value = request_headers.get(key);
req.append(key + ": " + value + "\r\n");
}
}
/** HTTP GET using url.
* Writes content to OutputStream.
*/
public boolean get(String url, OutputStream os) {
if (debug) {
JFLog.log("HTTP.get():" + url);
}
code = -1;
if (s == null) return false;
StringBuilder req = new StringBuilder();
req.append("GET " + url + " HTTP/1.1\r\n");
req.append("Host: " + host + (port != 80 ? (":" + port) : "") + "\r\n");
req.append("Content-Length: 0\r\n");
req.append("Accept: */*\r\n");
req.append("Accept-Encoding: chunked\r\n");
appendHeaders(req);
req.append("\r\n");
if (debug) {
JFLog.log("request=" + req.toString());
}
try {
sendRequest(req.toString());
return getReply(os);
} catch (Exception e) {
JFLog.log(e);
return false;
}
}
/** HTTP GET using url.
* Returns as a byte[]
*/
public byte[] get(String url) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (!get(url, baos)) return null;
return baos.toByteArray();
}
/** HTTP GET using url.
* Returns as a String.
*/
public String getString(String url) {
return new String(get(url));
}
/** HTTP POST using url with post data encoding with mimeType.
* Writes content to OutputStream.
*/
public boolean post(String url, byte[] data, String mimeType, OutputStream os) {
code = -1;
if (s == null) return false;
StringBuilder req = new StringBuilder();
req.append("POST " + url + " HTTP/1.1\r\n");
req.append("Host: " + host + (port != 80 ? (":" + port) : "") + "\r\n");
req.append("Content-Length: " + data.length + "\r\n");
req.append("Content-Type: " + mimeType + "\r\n");
req.append("Accept: */*\r\n");
req.append("Accept-Encoding: chunked\r\n");
appendHeaders(req);
req.append("\r\n");
try {
sendRequest(req.toString());
sendData(data);
return getReply(os);
} catch (Exception e) {
JFLog.log(e);
return false;
}
}
/** HTTP POST using url with post data encoding with mimeType.
* Returns content as byte[]
*/
public byte[] post(String url, byte[] data, String mimeType) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (!post(url, data, mimeType, baos)) return null;
return baos.toByteArray();
}
/** HTTP POST using url with post data encoding with mimeType.
* Returns content as String.
*/
public String postString(String url, byte[] data, String mimeType) {
return new String(post(url, data, mimeType));
}
/** Test HTTP */
public static void main(String[] args) {
HTTP http = new HTTP();
String html;
boolean print = false;
if (args.length > 0 && args[0].equals("print")) print = true;
debug = true;
http.open("google.com");
html = http.getString("/");
http.close();
if (html == null || html.length() == 0) {
System.out.println("Error:HTTP.get() failed");
return;
}
if (print) System.out.println(html);
http.open("www.google.com");
html = http.getString("/");
http.close();
if (html == null || html.length() == 0) {
System.out.println("Error:HTTP.get() failed");
return;
}
if (print) System.out.println(html);
}
/**
* Returns HTTP style parameter from list of parameters.
*
* @param params = HTTP list of parameters
* @param name = name of parameter to return
* @return parameter
*/
public static String getParameter(String[] params, String name) {
for(int a=0;a<params.length;a++) {
String param = params[a];
int idx = param.indexOf(":");
if (idx == -1) continue;
String key = param.substring(0, idx).trim();
String value = param.substring(idx + 1).trim();
if (key.equalsIgnoreCase(name)) {
return value;
}
}
return null;
}
/**
* Returns HTTP style parameter(s) from list of parameters.
*
* @param params = HTTP list of parameters
* @param name = name of parameter to return
* @return parameter(s)
*/
public static String[] getParameters(String[] params, String name) {
ArrayList<String> lst = new ArrayList<>();
for(int a=0;a<params.length;a++) {
String param = params[a];
int idx = param.indexOf(":");
if (idx == -1) continue;
String key = param.substring(0, idx).trim();
String value = param.substring(idx + 1).trim();
if (key.equalsIgnoreCase(name)) {
lst.add(value);
}
}
return lst.toArray(JF.StringArrayType);
}
/**
* Get Content from a HTTP message.
*/
public static String[] getContent(String[] msg) {
ArrayList<String> content = new ArrayList<String>();
for (int a = 0; a < msg.length; a++) {
//look for double \r\n (which appears as an empty line) that marks end of headers
if (msg[a].length() == 0) {
for (int b = a + 1; b < msg.length; b++) {
content.add(msg[b]);
}
break;
}
}
return content.toArray(JF.StringArrayType);
}
}