2017년 1월 16일 월요일

Android에서 REST client 구현 관련.. TLS 1.2 지원

예전에 구현했던 것을 다시 업데이트 하다 보니
많은 부분이 변경이 되어 관련 정리를 해봄.

일단 REST architecture 개념은 다음 논문을 참고하시라.
http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm


먼저 HTTPS 연결이 안드로이드 내부에서 자동으로 되는 것 같음.
예전에는 별도 class를 만들어서 연결 했었던 것 같은데

https://developer.android.com/training/articles/security-ssl.html#HttpsExample

잘 알려진 CA가 발급한 인증서가 여러분의 웹 서버에 있다고 가정하면, 다음과 같은 간단한 코드로 보안 요청을 수행할 수 있습니다.
URL url = new URL("https://wikipedia.org");
URLConnection urlConnection = url.openConnection();
InputStream in = urlConnection.getInputStream();
copyInputStreamToOutputStream(in, System.out);
그렇습니다. 정말로 이렇게 간단합니다. 맞춤형 HTTP 요청을 수행하려면, HttpURLConnection으로 캐스트하면 됩니다. HttpURLConnection의 Android 문서에는 더 자세한 예시가 있으며, 이 예시에서는 요청과 응답 헤더 처리, 콘텐츠 게시, 쿠키 관리, 프록시 사용, 응답 캐싱 등에 대해 설명합니다. 그러나 인증서와 호스트 이름을 확인하는 자세한 절차는 Android 프레임워크가 이러한 API를 통해 자동으로 처리합니다. 가능하면 여기에서 모든 것을 해결할 수 있습니다. 하지만, 아래와 같은 다른 고려사항도 있습니다.

기본적인 HTTPURLConnection 사용법은 다음과 같음.

https://developer.android.com/reference/java/net/HttpURLConnection.html

URL url = new URL("http://www.android.com/");
   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   try {
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
   } finally {
     urlConnection.disconnect();
   }

정말 간단하고
REST client를 만들기 위해서 필요한 method 조정이나 upload 관련 부분도 API를 지원해서 간단하게 처리할 수 있을 것 같음.

HTTP Methods

HttpURLConnection uses the GET method by default. It will use POST if setDoOutput(true) has been called. Other HTTP methods (OPTIONSHEADPUTDELETE and TRACE) can be used with setRequestMethod(String).

Posting Content

To upload data to a web server, configure the connection for output using setDoOutput(true).
For best performance, you should call either setFixedLengthStreamingMode(int) when the body length is known in advance, or setChunkedStreamingMode(int) when it is not. Otherwise HttpURLConnection will be forced to buffer the complete request body in memory before it is transmitted, wasting (and possibly exhausting) heap and increasing latency.
For example, to perform an upload:
   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   try {
     urlConnection.setDoOutput(true);
     urlConnection.setChunkedStreamingMode(0);

     OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
     writeStream(out);

     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
   } finally {
     urlConnection.disconnect();
   }


근데...

TLS 1.2 지원에 좀 문제가 있는지 지원을 안하는지..
개발 중인 서비스 서버에 연결이 제대로 안된다.
일단 예전에 사용하던 방식을 다시 사용하긴 했는데 찾아보니 다른 방법들도 꽤 있는 것 같음.

일단은 그냥 사용하게 된 예전 코드
 : https://github.com/hallower/wimple/blob/master/app/src/main/java/kr/blogspot/charlie0301/wimple/impl/RestAPIInvoker.java#L49



댓글 없음:

댓글 쓰기