File tree Expand file tree Collapse file tree
main/java/com/retailsvc/http/internal
test/java/com/retailsvc/http/internal Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .retailsvc .http .internal ;
2+
3+ import java .nio .charset .Charset ;
4+ import java .nio .charset .IllegalCharsetNameException ;
5+ import java .nio .charset .StandardCharsets ;
6+ import java .nio .charset .UnsupportedCharsetException ;
7+
8+ /** Decodes a text/plain request body using the charset declared on {@code Content-Type}. */
9+ public final class TextPlainParser {
10+
11+ public String parse (byte [] body , String contentTypeHeader ) {
12+ Charset charset = resolveCharset (contentTypeHeader );
13+ return new String (body , charset );
14+ }
15+
16+ private static Charset resolveCharset (String header ) {
17+ return ContentTypeHeader .parameter (header , "charset" )
18+ .map (TextPlainParser ::safeCharset )
19+ .orElse (StandardCharsets .UTF_8 );
20+ }
21+
22+ private static Charset safeCharset (String name ) {
23+ try {
24+ return Charset .forName (name );
25+ } catch (IllegalCharsetNameException | UnsupportedCharsetException _) {
26+ return StandardCharsets .UTF_8 ;
27+ }
28+ }
29+ }
Original file line number Diff line number Diff line change 1+ package com .retailsvc .http .internal ;
2+
3+ import static org .assertj .core .api .Assertions .assertThat ;
4+
5+ import java .nio .charset .StandardCharsets ;
6+ import org .junit .jupiter .api .Test ;
7+
8+ class TextPlainParserTest {
9+
10+ private final TextPlainParser parser = new TextPlainParser ();
11+
12+ @ Test
13+ void decodesUtf8ByDefault () {
14+ String body = "hello världen" ;
15+ assertThat (parser .parse (body .getBytes (StandardCharsets .UTF_8 ), null )).isEqualTo (body );
16+ }
17+
18+ @ Test
19+ void respectsCharsetFromHeader () {
20+ String body = "räksmörgås" ;
21+ byte [] bytes = body .getBytes (StandardCharsets .ISO_8859_1 );
22+ assertThat (parser .parse (bytes , "text/plain; charset=iso-8859-1" )).isEqualTo (body );
23+ }
24+
25+ @ Test
26+ void emptyBodyDecodesToEmptyString () {
27+ assertThat (parser .parse (new byte [0 ], null )).isEqualTo ("" );
28+ }
29+
30+ @ Test
31+ void unknownCharsetFallsBackToUtf8 () {
32+ String body = "hello" ;
33+ assertThat (parser .parse (body .getBytes (StandardCharsets .UTF_8 ), "text/plain; charset=bogus" ))
34+ .isEqualTo (body );
35+ }
36+ }
You can’t perform that action at this time.
0 commit comments