태그 보관물: URL

Java에서 Javascript의 encodeURIComponent 구현하기

자바에서는 URLEncoder를 사용해서 인코딩을 할 수 있는데 자바스크립트에서 사용하는 encodeURIComponent와 살짝 다르다.

Java의 URLEncoder:

  • literal characters (regex representation): [-a-zA-Z0-9._*]
  • the space character " " is converted into a plus sign "+".

JavaScript의 encodeURIComponent():

  • literal characters (regex representation): [-a-zA-Z0-9._*~'()!]

즉, 자바에서는 빈칸을 ‘+‘로 바꾸고 자바스크립트는 빈칸을 ‘%20‘으로 변환,
그리고 자바스크립트에서는 ~'()!을 그대로 두지만 자바에서는 각각 UTF-8 인코딩시킨다.

결국 빈칸과 ~'()!을 변환시키면 URLEncoder의 결과를 encodeURIComponent의 결과와 동일하게 만들 수 있다.

 

public static String encodeURIComponent(String s)
  {
    String result = null;
 
    try
    {
      result = URLEncoder.encode(s, "UTF-8")
                         .replaceAll("\\+", "%20")
                         .replaceAll("\\%21", "!")
                         .replaceAll("\\%27", "'")
                         .replaceAll("\\%28", "(")
                         .replaceAll("\\%29", ")")
                         .replaceAll("\\%7E", "~");
    }
 
    // This exception should never occur.
    catch (UnsupportedEncodingException e)
    {
      result = s;
    }
 
    return result;
  }

안드로이드에서 개발한 앱과 서버간의 통신이 제대로 안되어 헤맸었는데 빈칸이 다르게 변환되는 것이 문제였다.

Java equivalent to JavaScript’s encodeURIComponent that produces identical output?

URL의 최대 길이는?

따로 HTTP 프로토콜 스펙에 정의되어 있지는 않으며
웹브라우져와 서버의 제한이 다르다.

<웹브라우저>

Microsoft Internet Explorer

2083자까지 가능하다.

Firefox

Firefox 1.5.x에서 65,536자까지 출력이 가능했으며 그 이상도 동작. 글 작성한 분이 10만자까지 테스트했다고 한다.

Safari

80,000자까지 테스트했을 때 동작하였다고 한다.

Opera

190,000자까지 테스트했을 때 동작하였다고 한다.

 

<웹서버>

Apache

4000자 정도에서 “413 Entity Too Large” 에러가 발생

Microsoft IIS

기본 제한은 16,384자이며 수정가능하다.

Perl HTTP::Daemon (Server)

8000자까지 동작

http://www.boutell.com/newfaq/misc/urllength.html