-
Notifications
You must be signed in to change notification settings - Fork 0
/
Request.java
520 lines (358 loc) · 11.7 KB
/
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
import java.io.*;
import java.net.*;
import java.util.*;
/**
* This class reprsent a HTTP request with GET method
*
*
* @author Mohammad Mahdi Malmasi
* @version 0.3.5
*/
public class Request implements Serializable
{
/* Fields */
protected static final String USER_AGENT = " Jurl - Insomnia";
protected static final String ACCEPT = "*/*";
// String of url
protected final String urlString;
// the request receiver
protected URL url = null;
// connection of this request
protected transient HttpURLConnection connection = null;
// a name for this request (use as file name that this request will save in it)
protected String requestName;
// group name of this request
protected String groupName;
// kind of the request
protected RequestKinds requestKind = RequestKinds.GET;
// headers <header key, header value>
protected HashMap<String, String> requestHeaders = null;
// follow redirect or not
protected boolean followRedirect = false;
// response code
protected int responseCode;
// response message
protected String responseMessage;
// this.endTime - this.startTime
protected long responseTime;
// size of the resposnse
protected long responseSize;
// response headers
protected HashMap<String, String> responseHeaders = new HashMap<>();
// format of the response body
protected String responseBodyFormat = null;
// user args for this req
private String reqDetails = null;
// check first send
protected boolean check = true;
// show in terminal or not
protected boolean showResponseHeaders = true;
// serial version UID
protected static final long serialVersionUID = 2215266465311155162L;
/* Constructor */
/**
* Create new Request GET with given details
*
*
* @param name : a name for this request
* @param group : name of the this request group
* @param url : url for send this requst
* @param headers : a {@code String} of request headers in this format: "header:value,header1:value1, ..."
* @param query : a {@code String} of request query in this format: "name=value&name1=value1& ..."
* @param followRedirect : set it {@code true} if you want follow redirect
* @param showResponseHeaders : show the result on terminal or not
* @param reqDetails : user given args for this requset
*
* @throws IOException make sure that given url has protocol and you are cannected to the internet
*/
public Request(String name, String group, String url, String headers, String query, boolean followRedirect, boolean showResponseHeaders, String reqDetails)
throws IOException
{
// set name and group
requestName = name;
groupName = group;
this.reqDetails = reqDetails;
// set url and query
url = checkURL(url);
this.urlString = checkAndSetQuery(url, query);
this.url = new URL(url);
// set request method
requestKind = RequestKinds.GET;
// set requst headers
requestHeaders = new HashMap<>();
buildHeaders(headers);
this.followRedirect = followRedirect;
this.showResponseHeaders = showResponseHeaders;
}
/* Methods */
// * setter mothods *
/**
* @param requestKind : set the method of this request
*/
public void setRequestKind(String requestKind)
{
this.requestKind = RequestKinds.getKind(requestKind);
}
// * getter methods *
/**
* @return name of this request
*/
public String getRequestName() { return requestName; }
/**
* @return the url of this request
*/
public URL getUrl() { return url; }
/**
* @return kind of this request
*/
public RequestKinds getRequestKind() { return requestKind; }
/**
* @return a {@code Set} of headers keys
*/
public Set<String> getrequestHeadersKeys()
{
if (requestHeaders == null)
return null;
return requestHeaders.keySet();
}
/**
* @return the value of given key
*/
public String getRequestHeader(String key)
{
if (requestHeaders != null)
return requestHeaders.get(key);
return null;
}
/**
* @return response code of this request
*/
public int getResponseCode() { return responseCode; }
/**
* @return response message of this request
*/
public String getResponseMessage() { return responseMessage; }
/**
* @return a {@code Set} of response headers keys
*/
public Set<String> getResponseHeaders() { return responseHeaders.keySet(); }
/**
* @return the value of given key
*/
public String getResponseHeader(String key) { return responseHeaders.get(key); }
/**
* @return response content length
*/
public long getResponseSize() { return responseSize; }
/**
* @return format of the response body
*/
public String getResponseBodyFormat() { return responseBodyFormat; }
/**
* @return time of resopnse to this request (ms)
*/
public long getResponseTime() { return responseTime; }
/**
* @return user given args for this request
*/
public String getReqDetails() { return reqDetails; }
/**
* @return {@code true} if this request follows redirects
*/
public boolean isFollowRedirects()
{
return followRedirect;
}
/**
* @return {@code true} if this request shows response headers
*/
public boolean isShowResponseHeaders() { return showResponseHeaders; }
/**
* This method send request and read the response
*/
public void run()
{
HttpURLConnection.setFollowRedirects(false);
// for first time
if (check)
{
try{ url = new URL(urlString); }
catch(MalformedURLException e) {Out.printErrors("internet");}
}
try{ connection = (HttpURLConnection) url.openConnection(); }
catch (IOException e) { Out.printErrors("internet"); }
try{ connection.setRequestMethod(RequestKinds.getKind(requestKind)); }
catch (ProtocolException | SecurityException e) { return; }
setHeaders();
long startTime = System.nanoTime();
long endTime = 0;
// send request and get response
try
{
connection.connect();
endTime = System.nanoTime();
responseCode = connection.getResponseCode();
responseMessage = connection.getResponseMessage();
responseSize = connection.getContentLengthLong();
readResponseHeaders();
setResponseBodyFormat();
}
catch(IOException e) { Out.printErrors("internet"); }
// set response time
responseTime = (endTime - startTime) / 1000000;
if (check)
{
Out.printRequestDetails(this);
check = false;
}
if (showResponseHeaders)
Out.printResponseDetails(this);
// for redirects
if (followRedirect && (responseCode/100 == 3))
{
String newUrl = connection.getHeaderField("Location");
try { this.url = new URL(newUrl); }
catch (MalformedURLException e) { System.out.println('I'); }
this.run();
return;
}
// check streams
if (connection.getErrorStream() != null)
{
try{ responseSize = Out.printResponseBody(connection.getErrorStream()); }
catch(IOException e){}
}
else
{
try{ responseSize = Out.printResponseBody(connection.getInputStream()); }
catch(IOException e){}
}
// disconnect the connectons
connection.disconnect();
}
/**
* This method add a new header to the request
*
*
* @param key : key of header
* @param value : value of header
*/
public void addHeader(String key, String value)
{
requestHeaders.put(key, value);
}
/**
* This method save this object to given group
* This file will save to a file with name of this request
*/
public void saveToFile()
{
try
{
DataBase.saveRequest(groupName, requestName, this);
}
catch (IOException e) { Out.printErrors("save"); }
}
/**
* This method set the headers of the request
*/
protected void setHeaders()
{
for (String key : requestHeaders.keySet())
connection.setRequestProperty(key, requestHeaders.get(key));
}
/**
* This method fill requsetHeaders hashMap by given string
*
* @param headers : a {@code String} of headers
*/
protected void buildHeaders(String headers)
{
requestHeaders.put("User-Agent", USER_AGENT);
requestHeaders.put("Accept", ACCEPT);
if (headers == null || headers.equals(""))
return;
String[] holdDatas = headers.split(",");
String key = null, value = null;
for (String data : holdDatas)
{
try
{
key = data.substring(0, data.indexOf(':'));
value = data.substring(data.indexOf(':')+1);
if (value.length() == 0 || key.length() == 0)
System.out.println('H');
}
catch (IndexOutOfBoundsException e) { System.out.println('H'); }
requestHeaders.put(key, value);
}
}
/**
* This method read the response headers
*/
protected void readResponseHeaders()
{
responseHeaders.put("details", connection.getHeaderField(null));
for (String key : connection.getHeaderFields().keySet())
{
if (key == null)
continue;
responseHeaders.put(key, connection.getHeaderField(key));
}
}
protected void setResponseBodyFormat()
{
if (responseHeaders.get("Content-Type") == null)
return;
String type = responseHeaders.get("Content-Type");
if (type.contains(";"))
responseBodyFormat = "." + type.substring(type.indexOf('/')+1, type.indexOf(";"));
else
responseBodyFormat = "." + type.substring(type.indexOf('/')+1);
}
/**
* This method check and set query
*
*
* @param url : requset url
* @param query : a {@code String} of query
*
* @return new url with query
*/
protected String checkAndSetQuery(String url, String query)
{
if (query == null)
return url;
String[] holdDatas = query.split("&");
String key = null;
for (String data : holdDatas)
{
try
{
key = data.substring(0, data.indexOf('='));
if (key.length() == 0)
System.out.println('Q');
}
catch (IndexOutOfBoundsException e) { System.out.println('Q'); }
}
if (url.charAt(url.length()-1) != '/')
url = url.concat("/");
return url.concat("?").concat(query);
}
/**
* This method set the url protocol to http
*
*
* @param url : url of this request
* @return return url with protocol
*/
protected String checkURL(String url)
{
try
{
if ((url.substring(0, 7)).equals("http://"))
return url;
} catch (StringIndexOutOfBoundsException e) {}
return "http://" + url;
}
}