Skip to content

Instantly share code, notes, and snippets.

@skuzzle
Created May 4, 2021 06:37
Show Gist options
  • Save skuzzle/a50a6f413ce287cdba6db83d901204bc to your computer and use it in GitHub Desktop.
Save skuzzle/a50a6f413ce287cdba6db83d901204bc to your computer and use it in GitHub Desktop.
Manually handling UTF-8 encoding failures
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.StandardCharsets;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
@PostMapping("/")
public String test(@RequestBody byte[] body) throws CharacterCodingException, UnsupportedEncodingException {
final CharsetDecoder newDecoder = StandardCharsets.UTF_8.newDecoder();
final CharBuffer decode = newDecoder.decode(ByteBuffer.wrap(body));
return decode.toString();
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = { CharacterCodingException.class, UnsupportedEncodingException.class })
void handleEncodingFuckup(Exception e) {
}
}
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class AppTest {
@Autowired
private TestRestTemplate testResttemplate;
@Test
void testPostWrongEncoding() throws Exception {
final byte[] body = "Tölzer Str.".getBytes("ISO-8859-1");
final ResponseEntity<String> forEntity = testResttemplate.postForEntity("/", body, String.class);
assertThat(forEntity.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
}
@Test
void testPostCorrectEncoding() throws Exception {
final byte[] body = "Tölzer Str.".getBytes("UTF-8");
final ResponseEntity<String> forEntity = testResttemplate.postForEntity("/", body, String.class);
assertThat(forEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment