Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

HttpBodyDecoder.java 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package com.silkimen.http;
  2. import java.nio.ByteBuffer;
  3. import java.nio.charset.CharacterCodingException;
  4. import java.nio.charset.Charset;
  5. import java.nio.charset.CharsetDecoder;
  6. import java.nio.charset.CodingErrorAction;
  7. import java.nio.charset.MalformedInputException;
  8. public class HttpBodyDecoder {
  9. private static final String[] ACCEPTED_CHARSETS = new String[] { "UTF-8", "ISO-8859-1" };
  10. public static String decodeBody(byte[] body, String charsetName)
  11. throws CharacterCodingException, MalformedInputException {
  12. return decodeBody(ByteBuffer.wrap(body), charsetName);
  13. }
  14. public static String decodeBody(ByteBuffer body, String charsetName)
  15. throws CharacterCodingException, MalformedInputException {
  16. if (charsetName == null) {
  17. return tryDecodeByteBuffer(body);
  18. } else {
  19. return decodeByteBuffer(body, charsetName);
  20. }
  21. }
  22. private static String tryDecodeByteBuffer(ByteBuffer buffer)
  23. throws CharacterCodingException, MalformedInputException {
  24. for (int i = 0; i < ACCEPTED_CHARSETS.length - 1; i++) {
  25. try {
  26. return decodeByteBuffer(buffer, ACCEPTED_CHARSETS[i]);
  27. } catch (MalformedInputException e) {
  28. continue;
  29. } catch (CharacterCodingException e) {
  30. continue;
  31. }
  32. }
  33. return decodeBody(buffer, ACCEPTED_CHARSETS[ACCEPTED_CHARSETS.length - 1]);
  34. }
  35. private static String decodeByteBuffer(ByteBuffer buffer, String charsetName)
  36. throws CharacterCodingException, MalformedInputException {
  37. return createCharsetDecoder(charsetName).decode(buffer).toString();
  38. }
  39. private static CharsetDecoder createCharsetDecoder(String charsetName) {
  40. return Charset.forName(charsetName).newDecoder().onMalformedInput(CodingErrorAction.REPORT)
  41. .onUnmappableCharacter(CodingErrorAction.REPORT);
  42. }
  43. }