java

JAVA - OS, Browser 체크하기 로직 개선

May 29, 2020

ua-parser를 사용해보자.

1. 레거시 코드

public String getOperationSystem(HttpServletRequest request) {
    // OS 구분
    String agent = request.getHeader("User-Agent");

    String os = null;

    if (agent != null) {
        if (agent.indexOf("NT 6.0") != -1) os = "Windows Vista/Server 2008";
        else if (agent.indexOf("NT 5.2") != -1) os = "Windows Server 2003";
        else if (agent.indexOf("NT 5.1") != -1) os = "Windows XP";
        else if (agent.indexOf("NT 5.0") != -1) os = "Windows 2000";
        else if (agent.indexOf("NT") != -1) os = "Windows NT";
        else if (agent.indexOf("9x 4.90") != -1) os = "Windows Me";
        else if (agent.indexOf("98") != -1) os = "Windows 98";
        else if (agent.indexOf("95") != -1) os = "Windows 95";
        else if (agent.indexOf("Win16") != -1) os = "Windows 3.x";
        else if (agent.indexOf("Windows") != -1) os = "Windows";
        else if (agent.indexOf("Linux") != -1) os = "Linux";
        else if (agent.indexOf("Macintosh") != -1) os = "mac";
        else os = "";
    } else {
        os = "";
    }


    return os;
}

기존 코드는 User-Agent를 String으로 받아서 일부 문자열이 일치하면 해당 OS로 판별하는 방식을 사용했다.
이 방식의 문제점은 계속해서 User-Agent 다양해질 경우 대응하기 어렵다는 점이다.

예를 들어 “98” 이라는 숫자가 User-Agent에 포함될 경우 무조건 OS를 Window 98로 인식한다는 것이다. “98” 은 다른 User-Agent에도 언제든지 나올 수 있다. 디바이스는 계속해서 추가될 것이기 때문이다.

2. ua-parser 라이브러리를 사용한다.

pom.xml

<!-- user-agent parser -->
<dependency>
    <groupId>com.github.ua-parser</groupId>
    <artifactId>uap-java</artifactId>
    <version>1.4.3</version>
</dependency>

테스트코드 작성

package xxx.xxx.xx.xxx.x.x.x.xxx

import static org.junit.Assert.assertEquals;

import java.io.IOException;
import org.junit.Test;
import ua_parser.Client;
import ua_parser.Parser;

public class UserAgentTest {

  Parser parser = new Parser();
  String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36";

  public CommonUtilTest() throws IOException {

  }

  @Test
  public void getBrowser() {
    Client client = parser.parse(userAgent);
    System.out.println(client.userAgent.family + client.userAgent.major + "." + client.userAgent.minor);
    assertEquals("Chrome83.0", client.userAgent.family + client.userAgent.major + "." + client.userAgent.minor);
  }

  @Test
  public void getOs() throws IOException {
    Client client = parser.parse(userAgent);
    System.out.println(client.os.family + " " + client.os.major);
    assertEquals("Windows 10", client.os.family + " " + client.os.major);
  }
}

3. Usage