Skip to content

Instantly share code, notes, and snippets.

@cx0der

cx0der/Helper.java

Created May 18, 2019
Embed
What would you like to do?
Helper methods
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
You can’t perform that action at this time.