Created
May 18, 2019 09:17
-
-
Save cx0der/bc917e10e33f0f0da9a17698228a3664 to your computer and use it in GitHub Desktop.
Helper methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private Map<String, String> parseRequestHeaders(BufferedReader in) throws IOException { | |
Map<String, String> headers = new HashMap<>(); | |
// parse the first line. | |
String header = in.readLine(); | |
StringTokenizer tokenizer = new StringTokenizer(header); | |
headers.put(METHOD, tokenizer.nextToken().toUpperCase()); | |
headers.put(RESOURCE, tokenizer.nextToken().toLowerCase()); | |
headers.put(PROTOCOL, tokenizer.nextToken()); | |
// Rest of the headers | |
String line; | |
while ((line = in.readLine()) != null && !line.isEmpty()) { | |
int idx = line.indexOf(':'); | |
if (idx > 0) { | |
headers.put(line.substring(0, idx).toLowerCase(), line.substring(idx + 1).trim()); | |
} | |
} | |
return headers; | |
} | |
private OutputStream getDataOutputStream(Map<String, String> requestHeaders, OutputStream outputStream) | |
throws IOException { | |
String acceptedEncoding = requestHeaders.getOrDefault(Http.Header.ACCEPT_ENCODING, ""); | |
if (acceptedEncoding.contains("gzip")) { | |
return new GZIPOutputStream(outputStream); | |
} | |
return new BufferedOutputStream(outputStream); | |
} | |
private String getContentEncoding(Map<String, String> requestHeaders) { | |
String acceptedEncoding = requestHeaders.getOrDefault(Http.Header.ACCEPT_ENCODING, ""); | |
return acceptedEncoding.contains(GZIP) ? GZIP : null; | |
} | |
private void writeResponseHeaders(PrintWriter out, String protocol, String status, String mimeType, String date, | |
int length, String contentEncoding) { | |
out.println(protocol + status); | |
out.println(SERVER + config.getProperty(SERVER_VERSION_PARAM)); | |
out.println(DATE + date); | |
if (contentEncoding != null) | |
out.println(CONTENT_ENCODING + contentEncoding); | |
out.println(CONTENT_TYPE + mimeType + ";charset=\"utf-8\""); | |
out.println(CONTENT_LENGTH + length); | |
out.println(CONNECTION + "close"); | |
out.println(); | |
out.flush(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment