https://everleaf.blogspot.com/search/label/PHP

10/17/2020

Java class simple http request GET POST PUT

Simple java http request GET POST PUT class, accept set custom header get response code, uri, header, body.Code java ini membutuhkan java class TrustedDomain.java.

code java class Request.java :


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
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import TrustedDomain;
 
/**
 *
 * @author everleaf.blogspot.com
 */
public class Request extends Thread {
 
    private HttpURLConnection request;
    private OutputStream requestoutputstream;
    private OutputStreamWriter requestoutputstreamwriter;
    private PrintWriter requestwriter;
    private InputStream requestgetstream;
    private final String boundary = "===" + System.currentTimeMillis() + "===";
    private final String linefeed = "\r\n";
    private String contenttype = "text/html";
    private Proxy proxyset;
    private boolean isproxy = false;
    private int RESPONSE_CODE = 0;
    private String RESPONSE_URI = "";
    private String RESPONSE_HEADER = "";
    private String RESPONSE_COOKIE = "";
    private String RESPONSE_CONTENT = "";
    private String POSTDATAUPLOAD = "";
    private int MAX_REDIRECT = 10;
 
    public Request() {
 
    }
     
    public boolean setmaxredirect(int maxredirect){
        this.MAX_REDIRECT = maxredirect;
        return true;
    }
 
    public boolean setssl() {
        HostnameVerifier allHostsValid;
        try {
            allHostsValid = TrustedDomain.TrustMe();
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        } catch (NoSuchAlgorithmException | KeyManagementException ex) {
            //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
        }
        return true;
    }
 
    public boolean set(String action) {
        switch (action) {
            case "POST":
                this.request.setDoOutput(true);
                this.request.setDoInput(true);
                break;
            case "GET":
                this.request.setDoInput(true);
                break;
            case "PUT":
                this.request.setDoOutput(true);
                try {
                    this.request.setRequestMethod(action);
                } catch (ProtocolException ex) {
                    //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
                }
                break;
 
            default:
                break;
        }
        return true;
    }
 
    public boolean setconnectiontimeout(int timeout) {
        this.request.setConnectTimeout(timeout);
        this.request.setReadTimeout(timeout);
        return true;
    }
 
    public boolean setheader(String header) {
        if (header.contains("&")) {
            String[] ampersand = header.split("&");
            for (String amp : ampersand) {
                if (amp.isEmpty() == false) {
                    String[] singleequal = amp.split("->");
                    if ((singleequal[0].equals("Content-Type")) || (singleequal[0].equals("content-type")) || (singleequal[0].equals("Content-type"))) {
                        if ((singleequal[1].contains("form-data"))) {
                            singleequal[1] = "multipart/form-data; boundary=" + this.boundary;
                            this.contenttype = "form-data";
                        } else {
                            this.contenttype = singleequal[1];
                        }
                    }
                    try {
                        this.request.addRequestProperty(singleequal[0], singleequal[1]);
                    } catch (java.lang.ArrayIndexOutOfBoundsException ex) {
                    }
                }
            }
        } else {
            String[] singleequal = header.split("->");
            if ((singleequal[0].equals("Content-Type")) || (singleequal[0].equals("content-type")) || (singleequal[0].equals("Content-type"))) {
                if ((singleequal[1].contains("form-data"))) {
                    singleequal[1] = "multipart/form-data; boundary=" + this.boundary;
                    this.contenttype = "form-data";
                } else {
                    this.contenttype = singleequal[1];
                }
            }
            try {
                this.request.addRequestProperty(singleequal[0], singleequal[1]);
            } catch (java.lang.ArrayIndexOutOfBoundsException ex) {
 
            }
        }
        return true;
    }
 
    public boolean setcookieBAK(String cookie) {
        if (cookie.contains("&")) {
            String[] ampersand = cookie.split("&");
            for (String sng : ampersand) {
                if (sng.isEmpty() == false) {
                    String[] singleequal = sng.split("->");
                    try {
                        this.request.addRequestProperty(singleequal[0], singleequal[1]);
                    } catch (java.lang.ArrayIndexOutOfBoundsException ex) {
 
                    }
                }
            }
        } else {
            String[] singleequal = cookie.split("->");
            try {
                this.request.addRequestProperty(singleequal[0], singleequal[1]);
            } catch (java.lang.ArrayIndexOutOfBoundsException ex) {
 
            }
        }
        return true;
    }
 
    public boolean setcookie(String cookie) {
        final String cookiey = cookie.replaceAll("(\\s+\\;?|\\;)$", "");
        final String cookieyx = cookiey.replaceAll("\\;\\;\\;\\;?|\\;\\;\\;?|\\;\\;", cookiey);
        this.request.addRequestProperty("Cookie", cookieyx);
        return true;
    }
 
    public boolean setpostdata(String postdata, boolean isurlencode) {
        if (this.contenttype.contains("text/plain")) {
            this.setpostdata_xwwwform(postdata, isurlencode);
        } else {
            if (this.contenttype.contains("application/x-www-form-urlencoded")) {
                this.setpostdata_xwwwform(postdata, isurlencode);
            } else {
                if (this.contenttype.contains("application/json")) {
                    this.setpostdata_json(postdata);
                } else {
                    if (this.contenttype.contains("form-data")) {
                        this.setpostdata_formdata(postdata, isurlencode);
                    }
                }
            }
        }
        return true;
    }
 
    public boolean setpostdata_xwwwform(String postdata, boolean isurlencode) {
        if (isurlencode) {
            String newpostdata = "";
            if (postdata.contains("&")) {
                String[] ampersand = postdata.split("&");
                for (String amp : ampersand) {
                    String[] singleequal = amp.split("->");
                    for (int t = 0; t < singleequal.length; t++) {
                        if (singleequal[t].isEmpty() == false) {
                            if (singleequal[t].isEmpty() == false) {
                                try {
                                    singleequal[t] = URLEncoder.encode(singleequal[t], "UTF-8");
                                } catch (UnsupportedEncodingException ex) {
                                    //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
                                }
                            }
                        }
                    }
                    try {
                        newpostdata += singleequal[0] + "=" + singleequal[1] + "&";
                    } catch (java.lang.ArrayIndexOutOfBoundsException ex) {
                        newpostdata += singleequal[0] + "=&";
                    }
                }
            } else {
                String[] singleequal = postdata.split("->");
                for (int t = 0; t < singleequal.length; t++) {
                    if (singleequal[t].isEmpty() == false) {
                        try {
                            singleequal[t] = URLEncoder.encode(singleequal[t], "UTF-8");
                        } catch (UnsupportedEncodingException ex) {
                            //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
                try {
                    newpostdata += singleequal[0] + "=" + singleequal[1] + "&";
                } catch (java.lang.ArrayIndexOutOfBoundsException ex) {
                    newpostdata += singleequal[0] + "=&";
                }
            }
            postdata = newpostdata.replaceAll("\\&$", "");
        } else {
            String newpostdata = postdata.replaceAll("\\-\\>", "=");
            postdata = newpostdata.replaceAll("\\&$", "");
        }
        byte[] data = postdata.getBytes(StandardCharsets.UTF_8);
        int content_length = data.length;
        this.request.setRequestProperty("Content-Length", Integer.toString(content_length));
        try {
            this.requestoutputstream = this.request.getOutputStream();
            this.requestoutputstream.write(data);
            this.requestoutputstream.flush();
            this.requestoutputstream.close();
        } catch (java.net.ConnectException ex) {
        } catch (javax.net.ssl.SSLHandshakeException ex) {
        } catch (IOException ex) {
            //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
        }
        return true;
    }
 
    public boolean setpostdata_json(String postdata) {
        try {
            this.requestoutputstream = request.getOutputStream();
            byte[] json = postdata.getBytes("utf-8");
            this.requestoutputstream.write(json, 0, json.length);
            this.requestoutputstream.flush();
            this.requestoutputstream.close();
        } catch (IOException ex) {
            //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
        }
        return true;
    }
 
    public boolean setpostdata_formdata(String postdata, boolean isurlencode) {
        try {
            this.requestoutputstream = request.getOutputStream();
            this.requestwriter = new PrintWriter(new OutputStreamWriter(this.requestoutputstream, "UTF-8"), true);
            if (postdata.contains("&")) {
                String[] ampersand = postdata.split("&");
                for (String amp : ampersand) {
                    String[] singleequal = amp.split("->");
                    if (isurlencode) {
                        for (int t = 0; t < singleequal.length; t++) {
                            if (singleequal[t].isEmpty() == false) {
                                singleequal[t] = URLEncoder.encode(singleequal[t], "UTF-8");
                            }
                        }
                    }
                    this.requestwriter.append("--" + this.boundary).append(this.linefeed);
                    this.requestwriter.append("Content-Disposition: form-data; name=\"" + singleequal[0] + "\"").append(this.linefeed);
                    this.requestwriter.append("Content-Type: text/plain; charset=UTF-8").append(this.linefeed);
                    this.requestwriter.append(this.linefeed);
                    try {
                        if (this.contenttype.equals("application/json")) {
                            this.requestwriter.append("{" + singleequal[1] + "}").append(this.linefeed);
                        } else {
                            this.requestwriter.append(singleequal[1]).append(this.linefeed);
                        }
                    } catch (java.lang.ArrayIndexOutOfBoundsException ex) {
                        if (this.contenttype.equals("application/json")) {
                            this.requestwriter.append("{}").append(this.linefeed);
                        } else {
                            this.requestwriter.append("").append(this.linefeed);
                        }
                    }
                }
            } else {
                String[] singleequal = postdata.split("->");
                if (isurlencode) {
                    for (int t = 0; t < singleequal.length; t++) {
                        if (singleequal[t].isEmpty() == false) {
                            singleequal[t] = URLEncoder.encode(singleequal[t], "UTF-8");
                        }
                    }
                }
                this.requestwriter.append("--" + this.boundary).append(this.linefeed);
                this.requestwriter.append("Content-Disposition: form-data; name=\"" + singleequal[0] + "\"").append(this.linefeed);
                this.requestwriter.append("Content-Type: text/plain; charset=UTF-8").append(this.linefeed);
                this.requestwriter.append(this.linefeed);
                try {
                    if (this.contenttype.equals("application/json")) {
                        this.requestwriter.append("{" + singleequal[1] + "}");
                    } else {
                        this.requestwriter.append(singleequal[1]).append(this.linefeed);
                    }
                } catch (java.lang.ArrayIndexOutOfBoundsException ex) {
                    if (this.contenttype.equals("application/json")) {
                        this.requestwriter.append("{}");
                    } else {
                        this.requestwriter.append("").append(this.linefeed);
                    }
                }
            }
            this.requestwriter.flush();
        } catch (IOException ex) {
            //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
        }
        return true;
    }
 
    public boolean setputdata(String rawputdata) {
        try {
            this.requestoutputstreamwriter = new OutputStreamWriter(this.request.getOutputStream());
            this.requestoutputstreamwriter.write(rawputdata);
            this.requestoutputstreamwriter.flush();
            this.requestoutputstreamwriter.close();
        } catch (Exception ex) {
            //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
        }
        return true;
    }
 
    public boolean setpostdatauploadfile(String postdata) {
        try {
            this.requestoutputstream = request.getOutputStream();
            this.requestwriter = new PrintWriter(new OutputStreamWriter(this.requestoutputstream, "UTF-8"), true);
            this.requestwriter.append("--" + this.boundary).append(this.linefeed);
            if (postdata.contains("&")) {
                String[] ampersand = postdata.split("&");
                for (String amp : ampersand) {
                    String[] singleequal = amp.split("->");
                    try {
                        this.requestwriter.append("Content-Disposition: form-data; name=\"" + singleequal[0] + "\"").append(this.linefeed);
                        this.requestwriter.append("Content-Type: text/plain; charset=UTF-8").append(this.linefeed);
                        this.requestwriter.append(this.linefeed);
                        this.requestwriter.append(singleequal[1]).append(this.linefeed);
                    } catch (java.lang.ArrayIndexOutOfBoundsException ex) {
                        this.requestwriter.append("Content-Disposition: form-data; name=\"" + singleequal[0] + "\"").append(this.linefeed);
                        this.requestwriter.append("Content-Type: text/plain; charset=UTF-8").append(this.linefeed);
                        this.requestwriter.append(this.linefeed);
                        this.requestwriter.append("").append(this.linefeed);
                    }
                }
            } else {
                String[] singleequal = postdata.split("->");
                try {
                    this.requestwriter.append("Content-Disposition: form-data; name=\"" + singleequal[0] + "\"").append(this.linefeed);
                    this.requestwriter.append("Content-Type: text/plain; charset=UTF-8").append(this.linefeed);
                    this.requestwriter.append(this.linefeed);
                    this.requestwriter.append(singleequal[1]).append(this.linefeed);
                } catch (java.lang.ArrayIndexOutOfBoundsException ex) {
                    this.requestwriter.append("Content-Disposition: form-data; name=\"" + singleequal[0] + "\"").append(this.linefeed);
                    this.requestwriter.append("Content-Type: text/plain; charset=UTF-8").append(this.linefeed);
                    this.requestwriter.append(this.linefeed);
                    this.requestwriter.append("").append(this.linefeed);
                }
            }
        } catch (IOException ex) {
            //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
        }
        this.requestwriter.append(this.linefeed);
        this.requestwriter.flush();
        return true;
    }
 
    public boolean setuploadfile(String varname, File file, String filename) {
        String contenttypefile = URLConnection.guessContentTypeFromName(filename);
        if (contenttypefile == null) {
            contenttypefile = "text/plain";
        }
        this.requestwriter.append("--" + this.boundary).append(this.linefeed);
        this.requestwriter.append("Content-Disposition: form-data; name=\"" + varname + "\"; filename=\"" + filename + "\"").append(this.linefeed);
        this.requestwriter.append("Content-Type:" + contenttypefile).append(this.linefeed);
        this.requestwriter.append("Content-Transfer-Encoding: binary").append(this.linefeed);
        this.requestwriter.append(this.linefeed);
        this.requestwriter.flush();
        try {
            FileInputStream inputstream = new FileInputStream(file);
            byte[] buffer = new byte[4096];
            int byteread = -1;
            while ((byteread = inputstream.read(buffer)) != -1) {
                this.requestoutputstream.write(buffer, 0, byteread);
            }
            this.requestoutputstream.flush();
            inputstream.close();
            this.requestwriter.append(this.linefeed);
            this.requestwriter.append("--" + this.boundary).append(this.linefeed);
            this.requestwriter.flush();
            this.requestwriter.close();
        } catch (FileNotFoundException ex) {
            //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
        }
 
        return true;
    }
 
    public boolean setproxy(String proxy, String type) {
        if (proxy.isEmpty() == false) {
            String[] semicol = proxy.split(":");
            switch (type) {
                case "HTTP":
                    this.proxyset = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(semicol[0], Integer.parseInt(semicol[1])));
                    this.isproxy = true;
                    break;
                case "SOCKS5":
                    this.proxyset = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(semicol[0], Integer.parseInt(semicol[1])));
                    this.isproxy = true;
                    break;
            }
        }
        return true;
    }
 
    public boolean seturl(String url) {
        if (this.isproxy) {
            try {
                this.request = (HttpURLConnection) new URL(url).openConnection(this.proxyset);
                this.request.setInstanceFollowRedirects(true);
            } catch (MalformedURLException ex) {
                //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            try {
                this.request = (HttpURLConnection) new URL(url).openConnection();
                this.request.setInstanceFollowRedirects(true);
            } catch (MalformedURLException ex) {
                //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return true;
    }
 
    private boolean getcookie() {
        this.RESPONSE_COOKIE = "";
        String headerName = null;
        for (int i = 1; (headerName = this.request.getHeaderFieldKey(i)) != null; i++) {
            if (headerName.equals("Set-cookie") || headerName.equals("Set-Cookie") || headerName.equals("set-cookie")) {
                this.RESPONSE_COOKIE += this.request.getHeaderField(i) + ";";
            } else {
            }
        }
        return true;
    }
 
    private boolean getheader() {
        Map<String, List<String>> map = this.request.getHeaderFields();
        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
            try {
                if (!(entry.getKey().equals("Cookie")) && !(entry.getKey().equals("Set-Cookie")) && !(entry.getKey().equals("set-cookie"))) {
                    this.RESPONSE_HEADER += entry.getKey() + "->" + entry.getValue().get(0) + "&";
                }
            } catch (java.lang.NullPointerException ex) {
            }
        }
        String e = this.RESPONSE_HEADER.replaceAll("\\&$", "");
        this.RESPONSE_HEADER = e;
        return true;
    }
 
    private boolean getcontent() {
        this.RESPONSE_URI = this.request.getURL().toString();
        try {
            this.RESPONSE_CODE = this.request.getResponseCode();
        } catch (Exception ex) {
            this.RESPONSE_CODE = 1996;
        }
        if (this.RESPONSE_CODE == HttpURLConnection.HTTP_OK
                || this.RESPONSE_CODE == HttpURLConnection.HTTP_CONFLICT
                || this.RESPONSE_CODE == HttpURLConnection.HTTP_MOVED_TEMP
                || this.RESPONSE_CODE == HttpURLConnection.HTTP_MOVED_PERM
                || this.RESPONSE_CODE == HttpURLConnection.HTTP_SEE_OTHER
                || this.RESPONSE_CODE == HttpURLConnection.HTTP_NOT_FOUND
                || this.RESPONSE_CODE == HttpURLConnection.HTTP_FORBIDDEN
                || this.RESPONSE_CODE == HttpURLConnection.HTTP_PAYMENT_REQUIRED
                || this.RESPONSE_CODE == HttpURLConnection.HTTP_UNAVAILABLE
                || this.RESPONSE_CODE == HttpURLConnection.HTTP_UNAUTHORIZED
                || this.RESPONSE_CODE == HttpURLConnection.HTTP_NOT_ACCEPTABLE
                || this.RESPONSE_CODE == HttpURLConnection.HTTP_BAD_METHOD
                || this.RESPONSE_CODE == HttpURLConnection.HTTP_BAD_REQUEST
                || this.RESPONSE_CODE == HttpURLConnection.HTTP_INTERNAL_ERROR
                || this.RESPONSE_CODE == 500) {
            if (this.RESPONSE_CODE >= 200 && this.RESPONSE_CODE < 400) {
                try {
                    this.requestgetstream = this.request.getInputStream();
                } catch (java.net.ConnectException ex) {
                } catch (IOException ex) {
                    //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                this.requestgetstream = this.request.getErrorStream();
            }
            try (BufferedReader buffer = new BufferedReader(new InputStreamReader(this.requestgetstream))) {
                String line = null;
                try {
                    while ((line = buffer.readLine()) != null) {
                        this.RESPONSE_CONTENT += line;
                    }
                } catch (java.net.SocketTimeoutException ex) {
                    this.RESPONSE_CONTENT = "notfound";
                }
                buffer.close();
                this.request.disconnect();
            } catch (java.net.SocketTimeoutException ex) {
                this.RESPONSE_CONTENT = "notfound";
                //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
            } catch (java.net.ConnectException ex) {
                this.RESPONSE_CONTENT = "notfound";
                //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
            } catch (java.util.NoSuchElementException ex) {
                this.RESPONSE_CONTENT = "notfound";
                //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
            } catch (javax.net.ssl.SSLHandshakeException ex) {
                this.RESPONSE_CONTENT = "notfound";
                //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
            } catch (java.net.SocketException ex) {
                this.RESPONSE_CONTENT = "notfound";
                //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
            } catch (java.lang.NullPointerException ex) {
                this.RESPONSE_CONTENT = "notfound";
                //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            this.RESPONSE_CONTENT = "website not responding";
        }
        return true;
    }
 
    private boolean checkredirect() {
        boolean redirect = false;
        try {
            this.RESPONSE_CODE = this.request.getResponseCode();
            if (this.RESPONSE_CODE != 0) {
                if (this.RESPONSE_CODE != HttpURLConnection.HTTP_OK) {
                    if (this.RESPONSE_CODE == HttpURLConnection.HTTP_MOVED_TEMP
                            || this.RESPONSE_CODE == HttpURLConnection.HTTP_MOVED_PERM
                            || this.RESPONSE_CODE == HttpURLConnection.HTTP_SEE_OTHER) {
                        redirect = true;
                    }
                }
                if (redirect && (this.MAX_REDIRECT > 0)) {
                    int amountredirect = this.MAX_REDIRECT - 1;
                    this.MAX_REDIRECT = amountredirect;
                    this.getcookie();
                    String useragent = this.request.getRequestProperty("User-Agent");
                    String location = this.request.getHeaderField("Location").replaceAll("www\\.", "");
                    if (Pattern.compile("https\\:\\/\\/?|http\\:\\/\\/").matcher(location).find()) {
                        Request requestnew = new Request();
                        requestnew.setmaxredirect(this.MAX_REDIRECT);
                        requestnew.setssl();
                        requestnew.seturl(location);
                        requestnew.set("GET");
                        requestnew.setheader("User-Agent->" + useragent + "&Upgrade-Insecure-Requests->1");
                        requestnew.setcookie(this.RESPONSE_COOKIE);
                        List<String> resp = requestnew.get();
                        this.RESPONSE_CODE = Integer.valueOf(resp.get(0));
                        this.RESPONSE_URI = resp.get(1);
                        this.RESPONSE_HEADER = resp.get(2);
                        this.RESPONSE_COOKIE = resp.get(3);
                        this.RESPONSE_CONTENT = resp.get(4);
                    }
                } else {
                    this.RESPONSE_URI = this.request.getURL().toString();
                }
            }
        } catch (java.net.SocketTimeoutException ex) {
            this.RESPONSE_URI = "null";
        } catch (java.net.ConnectException ex) {
            this.RESPONSE_URI = "null";
        } catch (java.util.NoSuchElementException ex) {
            this.RESPONSE_URI = "null";
        } catch (javax.net.ssl.SSLHandshakeException ex) {
            this.RESPONSE_URI = "null";
        } catch (java.net.SocketException ex) {
            this.RESPONSE_URI = "null";
        } catch (java.lang.NullPointerException ex) {
            this.RESPONSE_URI = "null";
        } catch (IOException ex) {
            this.RESPONSE_URI = "null";
        }
        return true;
    }
 
    public List<String> get() {
        List<String> returned = new ArrayList<String>();
        this.getcookie();
        this.getheader();
        this.getcontent();
        this.checkredirect();
        returned.add(String.valueOf(this.RESPONSE_CODE));
        returned.add(this.RESPONSE_URI);
        returned.add(this.RESPONSE_HEADER);
        returned.add(this.RESPONSE_COOKIE);
        returned.add(this.RESPONSE_CONTENT);
        return returned;
    }
 
    public List<String> post() {
        if (this.contenttype.equals("text/plain")) {
            try {
                this.requestoutputstream.flush();
                this.requestoutputstream.close();
                this.requestwriter.append(this.linefeed).flush();
                this.requestwriter.append("--" + this.boundary + "--").append(this.linefeed);
                this.requestwriter.close();
            } catch (IOException ex) {
                //Logger.getLogger(Request.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        List<String> returned = new ArrayList<String>();
        this.getcookie();
        this.getheader();
        this.getcontent();
        this.checkredirect();
        returned.add(String.valueOf(this.RESPONSE_CODE));
        returned.add(this.RESPONSE_URI);
        returned.add(this.RESPONSE_HEADER);
        returned.add(this.RESPONSE_COOKIE);
        returned.add(this.RESPONSE_CONTENT);
        return returned;
    }
 
    public List<String> put() {
        List<String> returned = new ArrayList<String>();
        this.getcookie();
        this.getheader();
        this.getcontent();
        this.checkredirect();
        returned.add(String.valueOf(this.RESPONSE_CODE));
        returned.add(this.RESPONSE_URI);
        returned.add(this.RESPONSE_HEADER);
        returned.add(this.RESPONSE_COOKIE);
        returned.add(this.RESPONSE_CONTENT);
        return returned;
    }
 
}

Deklarasi GET Request, simpan dengan nama ExampleGetRequest.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import Request;
 
public class ExampleGetRequest{
 
    public static void main(String args[]){
        Request request = new Request();
        //request.setproxy("127.0.0.1:8080", "HTTP"); #jika anda ingin menggunakan proxy HTTP atau SOCKS5
        request.setmaxredirect(10);
        request.setssl();
        request.seturl("https://your-example-website.com");
        request.set("GET");
        request.setconnectiontimeout(60000); //60s = 60000mils
        request.setheader("User-Agent->Mozilla 4&Header1->1");
        request.setcookie("session1->12345&session2->6789");
        List<String> response = request.get();
        System.out.println("Response code: "+response.get(0));
        System.out.println("Response uri: "+response.get(1));
        System.out.println("Response header: "+response.get(2));
        System.out.println("Response cookie: "+response.get(3));
        System.out.println("Response body: "+response.get(4));
    }
}
hasilnya:
1
2
3
4
5
Response code: 200
Response uri: https://your-example-website.com/index.php
Response header: Server->apache/2.4.2&User-Agent->Mozilla 4
Response cookie: session1=12345;session2=252525
Response body: <html>....

Deklarasi POST Request, simpan dengan nama ExamplePostRequest.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import Request;
 
public class ExamplePostRequest{
 
    public static void main(String args[]){
        Request request = new Request();
        //request.setproxy("127.0.0.1:8080", "HTTP"); #jika anda ingin menggunakan proxy HTTP atau SOCKS5
        request.setmaxredirect(10);
        request.setssl();
        request.seturl("https://your-example-website.com/data.php");
        request.set("POST");
        request.setconnectiontimeout(60000); //60s = 60000mils
        request.setheader("User-Agent->Mozilla 4&Header1->1&Content-Type->multipart/form-data");
        request.setcookie("session1->12345&session2->6789");
        request.setpostdata("data1->123&data2->12345");
        List<String> response = request.post();
        System.out.println("Response code: "+response.get(0));
        System.out.println("Response uri: "+response.get(1));
        System.out.println("Response header: "+response.get(2));
        System.out.println("Response cookie: "+response.get(3));
        System.out.println("Response body: "+response.get(4));
    }
}
hasilnya:
1
2
3
4
5
Response code: 200
Response uri: https://your-example-website.com/success.php
Response header: Server->apache/2.4.2&User-Agent->Mozilla 4
Response cookie: session1=12345;session2=252525
Response body: <html>....

Deklarasi PUT Request, simpan dengan nama ExamplePutRequest.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import Request;
 
public class ExamplePutRequest{
 
    public static void main(String args[]){
        Request request = new Request();
        //request.setproxy("127.0.0.1:8080", "HTTP"); #jika anda ingin menggunakan proxy HTTP atau SOCKS5
        request.setmaxredirect(10);
        request.setssl();
        request.seturl("https://your-example-website.com/data.php");
        request.set("PUT");
        request.setconnectiontimeout(60000); //60s = 60000mils
        request.setheader("User-Agent->Mozilla 4&Header1->1");
        request.setcookie("session1->12345&session2->6789");
        request.setputdata("abcd12345");
        List<String> response = request.put();
        System.out.println("Response code: "+response.get(0));
        System.out.println("Response uri: "+response.get(1));
        System.out.println("Response header: "+response.get(2));
        System.out.println("Response cookie: "+response.get(3));
        System.out.println("Response body: "+response.get(4));
    }
}
hasilnya:
1
2
3
4
5
Response code: 200
Response uri: https://your-example-website.com/data.php
Response header: Server->apache/2.4.2&User-Agent->Mozilla 4
Response cookie: session1=12345;session2=252525
Response body: <html>....

No comments:

Post a Comment

Diharapkan berkomentar dengan sopan dan santun, terimakasih.