ANDROID/Android 개발 이슈 & 해결

[Android] Retrofit2 연결 오류 해결 - java.net.UnknownServiceException, java.net.SocketTimeoutException

주 녕 2021. 10. 25. 15:13
728x90

프로젝트를 하면서 외부 DB를 사용하게 되었다.

Retrofit을 이용하여 진행하게 되었는데, Google에서 제공한 test URL에서는 잘 작동했는데

백엔드 개발자 친구가 준 URL에서는 여러 오류들을 만나게 되었다. 우선 해당 URL은 아직 로컬 서버인 상태였다!

 

 

java.net.UnknownServiceException

java.net.UnknownServiceException: CLEARTEXT communication to ~ not permitted by network security policy

  • 발생 원인 : http 서버 호출 시 발생하는 에러인데, 안드로이드 9.0 부터는 보안상의 문제로 http 관련 호출을 차단한다. 
  • 해결 방법 2 : https로 호출하기 (권장 사항) -  근본적인 원인 해결 방안
  • 해결 방법 1 : default 값을 변경하기 - 근본적인 보안 문제 해결 방안은 아님(일시적)

AndroidManifest.xml

<application
    android:usesCleartextTraffic="true"
    ...>

res/xml/network_security_config.xml

<?xml version="1.0" encoding="utf-8"?> 
<network-security-config> 
    <domain-config cleartextTrafficPermitted="true"> 
        <domain includeSubdomains="true"> IP or 도메인 주소 </domain> 
    </domain-config> 
</network-security-config>

 

 

java.net.SocketTimeoutException

java.net.SocketTimeoutException: failed to connect to ~ from ~ after 10000ms

  • 타임아웃(Timeout) : 프로그램이 특정한 시간 내에 성공적으로 수행되지 않아 진행이 자동적으로 중단되는 것 
  • 소켓 타임아웃(SocketTimeout) : 클라이언트와 서버가 연결된 후에 서버는 데이터를 클라이언트에게 전송하는데, 이때 하나의 데이터를 여러 개의 패킷으로 나누어 전송하게 된다. 이 여러 개의 패킷이 각각 전송될 때의 시간 차이가 발생하는데 이 차이의 임계치를 말한다.
  • 해결 방법 1 : 연결 제한 시간(위에서 말한 임계치)를 늘린다.
  • 해결 방법 2 : 서버를 제대로 올린다... (우리는 이 방법이 맞았닿ㅎ)
728x90