|
| 1 | +package com.amazonaws.serverless.proxy.internal; |
| 2 | + |
| 3 | +import org.apache.commons.io.Charsets; |
| 4 | + |
| 5 | +import java.nio.charset.Charset; |
| 6 | +import java.nio.charset.StandardCharsets; |
| 7 | +import java.nio.charset.UnsupportedCharsetException; |
| 8 | + |
| 9 | +public final class HttpUtils { |
| 10 | + |
| 11 | + static final String HEADER_KEY_VALUE_SEPARATOR = "="; |
| 12 | + static final String HEADER_VALUE_SEPARATOR = ";"; |
| 13 | + static final String ENCODING_VALUE_KEY = "charset"; |
| 14 | + |
| 15 | + |
| 16 | + static public Charset parseCharacterEncoding(String contentTypeHeader,Charset defaultCharset) { |
| 17 | + // we only look at content-type because content-encoding should only be used for |
| 18 | + // "binary" requests such as gzip/deflate. |
| 19 | + if (contentTypeHeader == null) { |
| 20 | + return defaultCharset; |
| 21 | + } |
| 22 | + |
| 23 | + String[] contentTypeValues = contentTypeHeader.split(HEADER_VALUE_SEPARATOR); |
| 24 | + if (contentTypeValues.length <= 1) { |
| 25 | + return defaultCharset; |
| 26 | + } |
| 27 | + |
| 28 | + for (String contentTypeValue : contentTypeValues) { |
| 29 | + if (contentTypeValue.trim().startsWith(ENCODING_VALUE_KEY)) { |
| 30 | + String[] encodingValues = contentTypeValue.split(HEADER_KEY_VALUE_SEPARATOR); |
| 31 | + if (encodingValues.length <= 1) { |
| 32 | + return defaultCharset; |
| 33 | + } |
| 34 | + try { |
| 35 | + return Charsets.toCharset(encodingValues[1]); |
| 36 | + } catch (UnsupportedCharsetException ex) { |
| 37 | + return defaultCharset; |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + return defaultCharset; |
| 42 | + } |
| 43 | + |
| 44 | + |
| 45 | + static public String appendCharacterEncoding(String currentContentType, String newEncoding) { |
| 46 | + if (currentContentType == null || currentContentType.trim().isEmpty()) { |
| 47 | + return null; |
| 48 | + } |
| 49 | + |
| 50 | + if (currentContentType.contains(HEADER_VALUE_SEPARATOR)) { |
| 51 | + String[] contentTypeValues = currentContentType.split(HEADER_VALUE_SEPARATOR); |
| 52 | + StringBuilder contentType = new StringBuilder(contentTypeValues[0]); |
| 53 | + |
| 54 | + for (int i = 1; i < contentTypeValues.length; i++) { |
| 55 | + String contentTypeValue = contentTypeValues[i]; |
| 56 | + String contentTypeString = HEADER_VALUE_SEPARATOR + " " + contentTypeValue; |
| 57 | + if (contentTypeValue.trim().startsWith(ENCODING_VALUE_KEY)) { |
| 58 | + contentTypeString = HEADER_VALUE_SEPARATOR + " " + ENCODING_VALUE_KEY + HEADER_KEY_VALUE_SEPARATOR + newEncoding; |
| 59 | + } |
| 60 | + contentType.append(contentTypeString); |
| 61 | + } |
| 62 | + |
| 63 | + return contentType.toString(); |
| 64 | + } else { |
| 65 | + return currentContentType + HEADER_VALUE_SEPARATOR + " " + ENCODING_VALUE_KEY + HEADER_KEY_VALUE_SEPARATOR + newEncoding; |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments