콘텐츠로 건너뛰기

[java] oauth encoder

java에서 제공하는 java.net.URLEncoder.encode()와

oauth 규약에서 정의하는 encode()는 서로 다르다.
http://www.marcworrell.com/article-2943-en.html 에서 보면
oauth에서는 RFC3986 규약을 따르고 있으며,
알파벳, 숫자, -, ., _, ~는 인코딩하지 않기로 가이드하고 있다.
즉, URLEncoder를 그대로 사용할 수는 없어서 wrapping해서 사용하게 된다.
다음 코드와 같이 된다.
public class MyStringUtils {
  private static final String ENCODING = “UTF-8”;

  public static String encode(String str) {
    if (str == null) { // avoid NPE
      return “”;
    }

    try { // OAuth encodes some characters differently
      return URLEncoder.encode(str, ENCODING)
         .replace(“+”, “%20”).replace(“*”, “%2A”).replace(“%7E”, “~”);
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException(e.getMessage(), e);
    }
  }

  public static String decode(String str) {
    if (str == null) { // avoid NPE
      return “”;
    }

    try {
      return URLDecoder.decode(str, ENCODING);
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException(e.getMessage(), e);
    }
  }
}

+는 ” “(공백)을 URLEncoder로 인코딩한 결과이다.
즉, 공백은 %20으로 치환, *은 %2A로 치환, %7E로 치환된 ~은 원래대로 쓰고
나머지 문자열은 모두 URLEncoder와 동일한 룰을 적용하겠다는 의미가 된다.

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다