-
Notifications
You must be signed in to change notification settings - Fork 0
/
HttpResponse.java
212 lines (190 loc) · 7.44 KB
/
HttpResponse.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
import java.io.*;
import java.net.*;
import java.util.*;
import static SSHelpers.Util.*;
public class HttpResponse {
final static String CRLF = "\r\n";
/** How big is the buffer used for reading the object */
final static int BUF_SIZE = 8192;
/** Reply status and headers */
String version; // HTTP version, part of statusLine
int status; // HTTP status code, part of statusLine
String statusMessage; // part of statusLine
String statusLine = "";
String proxy = "SSProxy"; // self advertising + it helps to identify requests that have passed through the proxy
String headers = ""; // all headers, excluding the statusLine
Date lastModified;
Date expires;
String etag;
/* Body of reply */
ByteArrayOutputStream body = new ByteArrayOutputStream();
/** Read response from server. */
public HttpResponse(DataInputStream fromServer) {
/* Length of the object */
int length = -1;
boolean gotStatusLine = false;
/* First read status line and response headers */
try {
String line = fromServer.readLine();
// Parse HTTP headers
while (line != null && line.length() != 0) { // line != null to medigate java.lang.NullPointerException
if (!gotStatusLine) {
statusLine = line;
String[] tmp = line.split(" ", 3);
if (tmp.length == 3) {
this.version = tmp[0];
this.status = Integer.parseInt(tmp[1]);
this.statusMessage = tmp[2];
}
gotStatusLine = true;
} else {
headers += line + CRLF;
}
/* Get length of content as indicated by
* Content-Length header. Unfortunately this is not
* present in every response. Some servers return the
* header "Content-Length", others return
* "Content-length". You need to check for both
* here. */
if (line.toLowerCase(Locale.ROOT).startsWith("content-length")) {
String[] tmp = line.split(" ");
length = Integer.parseInt(tmp[1]);
}
else if (line.toLowerCase(Locale.ROOT).startsWith("last-modified")) {
String[] tmp = line.split(" ", 2);
lastModified = toDate(tmp[1]);
} else if (line.toLowerCase(Locale.ROOT).startsWith("expires")) {
String[] tmp = line.split(" ", 2);
expires = toDate(tmp[1]);
} else if (line.toLowerCase(Locale.ROOT).startsWith("etag")) {
String[] tmp = line.split(" ", 2);
etag = tmp[1];
}
line = fromServer.readLine();
}
} catch (IOException e) {
System.out.println("Error reading headers from server: " + e);
return;
}
try {
int bytesRead = 0;
byte buf[] = new byte[BUF_SIZE];
boolean loop = false;
/* If we didn't get Content-Length header, just loop until
* the connection is closed. */
if (length == -1) {
loop = true;
}
/* Read the body in chunks of BUF_SIZE and copy the chunk
* into body. Usually replies come back in smaller chunks
* than BUF_SIZE. The while-loop ends when either we have
* read Content-Length bytes or when the connection is
* closed (when there is no Connection-Length in the
* response. */
while (bytesRead < length || loop) {
/* Read it in as binary data */
int res = fromServer.read(buf);
if (res == -1) {
break;
}
/* Copy the bytes into body. Make sure we don't exceed
* the maximum object size. */
body.write(buf, 0, res);
bytesRead += res;
}
} catch (IOException e) {
// error = 500;
System.out.println("Error reading response body: " + e);
return;
}
}
// constructor for HTTP status codes
public HttpResponse(int statusCode) {
version = "HTTP/1.1";
status = statusCode;
switch (status) {
case 200:
statusMessage = "OK";
break;
case 400: // when headers are not properly formatted
statusMessage = "Bad request";
break;
case 404:
statusMessage = "Not found";
break;
case 405:
statusMessage = "Method not allowed";
break;
case 500:
statusMessage = "Internal server error";
break;
case 501: // for methods that are not implemented
statusMessage = "Not implemented";
break;
case 505: // for http/2
statusMessage = "HTTP version not supported";
break;
case 520:
statusMessage = "Unknown Error";
// used by Microsoft and CloudFlare as a "catch-all" response
// for when the origin server returns something unexpected
// or something that is not tolerated/interpreted.
break;
default:
System.out.println("Invalid HTTP status code");
status = 500;
statusMessage = "Internal server error";
}
statusLine = version + " " + status + " " + statusMessage;
String bodyStr = status + " " + statusMessage;
body.write(bodyStr.getBytes(), 0, bodyStr.length());
}
public HttpResponse setStaus(int status) {
this.status = status;
return this;
}
public HttpResponse setMessage(String message) {
this.statusMessage = message;
return this;
}
public HttpResponse setVersion(String version) {
this.version = version;
return this;
}
public byte[] getBody() {
return body.toByteArray();
}
/**
* Convert response into a string for easy re-sending. Only
* converts the response headers, body is not converted to a
* string.
*/
public String toString() {
String res = "";
res = statusLine + CRLF;
res += headers;
res += "X-Proxy-Agent: " + proxy + CRLF;
res += CRLF;
return res;
}
// send response to a host (generally the client)
public Socket send(Socket host) {
try {
// Write response to host.
DataOutputStream toClient = new DataOutputStream(host.getOutputStream());
toClient.writeBytes(toString());
ProxyCache.verbose("<--- Response <--- \n" + toString());
} catch (IOException e) {
System.out.println("Error writing response to client: " + e);
}
return host;
}
// check if response is still valid using the (now old) expires header
public boolean isExpired() {
if (lastModified != null && expires != null) {
Date now = new Date(); // get current date time
return !(now.after(lastModified) && now.before(expires)); // no web request is needed
}
return false;
}
}