컴퓨터/이론: 개발
[2017.10.26] 07. Node.js서버와 Android클라이언트 [데이터 통신 DB X]
heepie
2017. 10. 26. 01:44
도입
이번 포스팅에서는 Node.js서버와 Android클라이언트 사이에 DB를 사용하지 않고 데이터 통신을 실습 할 예정이다.
Node.js서버와 Android클라이언트 [데이터 통신 DB X]의 데이터 흐름

실습1 - GET 방식
Android 기본제공하는 LoginActivity를 수정해 사용했다.
Android sendDataGetMethod
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | public class Remote { // Post 데이터를 서버로 전송 public static String sendDataPostMethod(String address, Map postdata) { // ... } public static String sendDataGetMethod(String string) { final StringBuilder result = new StringBuilder(); try { // GET 방식은 전송할 데이터를 URL에 담아 전송한다. URL url = new URL(string); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); // 통신결과가 성공인지 확인 if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { // 파일 입출력과 동일 InputStreamReader isr = new InputStreamReader(conn.getInputStream()); BufferedReader br = new BufferedReader(isr); String tmp = ""; // 요청 결과를 가공 while ((tmp = br.readLine()) != null) { result.append(tmp); } br.close(); isr.close(); } else { Log.e("heepie", conn.getResponseCode()+""); } conn.disconnect(); } catch (Exception e) { Log.e("heepie", e.toString()); } return result.toString(); } } | cs |
GET 패킷

스크린 샷

실습2 - POST 방식
Android 기본제공하는 LoginActivity를 수정해 사용했다.
Android sendDataPostMethod
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | public class Remote { // Post 데이터를 서버로 전송 public static String sendDataPostMethod(String address, Map postdata) { final StringBuilder result = new StringBuilder(); try { URL url = new URL(address); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); String tmp = ""; // Post 방식은 전송할 데이터를 가공해 Body 안에 넣어 전송한다. for (Object key : postdata.keySet()) { tmp += "&"; tmp += key+"="+postdata.get(key); } tmp = tmp.substring(1); conn.setDoOutput(true); // 데이터를 전송할 OutputStream 가져온다. OutputStream os = conn.getOutputStream(); os.write(tmp.getBytes()); os.flush(); os.close(); // 통신결과가 성공인지 확인 if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { // 파일 입출력과 동일 InputStreamReader isr = new InputStreamReader(conn.getInputStream()); BufferedReader br = new BufferedReader(isr); tmp = ""; // 요청 결과를 가공 while ((tmp = br.readLine()) != null) { result.append(tmp); } br.close(); isr.close(); } else { Log.e("heepie", conn.getResponseCode()+""); } } catch (Exception e) { e.printStackTrace(); } return result.toString(); } // Get 데이터를 서버로 전송 public static String sendDataGetMethod(String string) { // ... } | cs |
POST 패킷

스크린 샷

#nodejs 서버 #몽고 db #mongo db