Node.js μ„œλ²„ Android 톡신(Retrofit)

AWS-Node.js μ„œλ²„ ꡬ좕 곡뢀.

Posted by Bangjinhyuk on February 19, 2021 · 17 mins read

aws μ„œλ²„ 와 Android 톡신 μ°Έμ‘°

ocr κΈ°λŠ₯을 μ‚¬μš©ν•˜μ—¬ μ‹œκ°„ν‘œμ •λ³΄λ“€μ„ μ˜¬λ°”λ₯΄κ²Œ κ°€μ Έμ˜€κΈ° μœ„ν•œ κΈ°λŠ₯ 기초 닀지기

  1. μ•ˆλ“œλ‘œμ΄λ“œ μŠ€νŠœλ””μ˜€ AndroidManifest.xml μ„€μ •

      <uses-permission android:name="android.permission.INTERNET" />
      <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
      <application
      ...
      android:usesCleartextTraffic="true">
    
  2. build.gradle에 Retrofit , okhttp3 μΆ”κ°€

     implementation 'com.squareup.retrofit2:retrofit:2.9.0'
     implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
     implementation com.squareup.retrofit2:converter-scalars:2.9.0'
        
     implementation 'com.squareup.okhttp3:okhttp:3.11.0'
     implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
    
  3. μ„œλ²„μ™€ 톡신할 λ©”μ†Œλ“œλ“€μ΄ λ‹΄κΈ΄ μΈν„°νŽ˜μ΄μŠ€λ₯Ό λ§Œλ“€μ–΄ μ€€λ‹€
     import java.util.Map;
    
     import retrofit2.Call;
     import retrofit2.http.Body;
     import retrofit2.http.GET;
     import retrofit2.http.POST;
     import retrofit2.http.Query;
     import retrofit2.http.QueryMap;
    
     public interface OcrFactory {
         @GET("ocr/connect") // <=μš”κΈ° μ•ˆμ— λ“€μ–΄κ°€λŠ”κ²Œ μ„œλ²„ path
         Call<String> connect(@Query("userEmail") String email);
    
         @GET("ocr/connecting") // <=μš”κΈ° μ•ˆμ— λ“€μ–΄κ°€λŠ”κ²Œ μ„œλ²„ path
         Call<Semester> connecting(@QueryMap Map<String, String> success);
    
         @POST("ocr/semester") // <=μš”κΈ° μ•ˆμ— λ“€μ–΄κ°€λŠ”κ²Œ μ„œλ²„ path
         Call<Res_semester> semester(@Body Req_semester user);
     }
    

    μΈν„°νŽ˜μ΄μŠ€μ—μ„œ 톡신 λΆ€λΆ„μ—μ„œ λŒ€λΆ€λΆ„μ˜ λ©”μ†Œλ“œλ“€μ„ λ‹€ λ„£μ„μˆ˜λ‘ 깔끔. λ˜λŠ” κΈ°λŠ₯λ³„λ‘œ λ‚˜λˆ„μ–΄ μΈν„°νŽ˜μ΄μŠ€ λΆ„λ₯˜ ν•˜κΈ°.

  4. ν•˜λ‚˜μ˜ μ„œλ²„μ™€ 톡신을 λ‹΄λ‹Ήν•˜λŠ” ν•˜λ‚˜μ˜ Singletone 클래슀 λ§Œλ“€κΈ°

    μ½”λ“œ 펼쳐보기
       ```java
       import com.google.gson.Gson;
       import com.google.gson.GsonBuilder;
    
       import okhttp3.OkHttpClient;
       import okhttp3.logging.HttpLoggingInterceptor;
       import retrofit2.Retrofit;
       import retrofit2.converter.gson.GsonConverterFactory;
       import retrofit2.converter.scalars.ScalarsConverterFactory;
    
       public class Net {
           private static Net ourinstance = new Net();
    
           public static Net getInstance(){
               return ourinstance;
           }
    
           Gson gson = new GsonBuilder().setLenient().create();
           private Net(){
           }
           OkHttpClient client = new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor()).build();
    
           private Retrofit retrofit = new Retrofit.Builder()
                   .baseUrl("") //<= μ„œλ²„ μ£Όμ†Œκ°’ μž…λ ₯
                   .client(client) //<= OkHttpClient 연동
                   .addConverterFactory(ScalarsConverterFactory.create()) //<= 고질적인 μ—λŸ¬ :JSON document was not fully consumed ν•΄κ²°
                   .addConverterFactory(GsonConverterFactory.create(gson))
                   .build();
           OcrFactory ocrFactory;
    
           public OcrFactory getOcrFactory(){
               if(ocrFactory == null){
                   ocrFactory = retrofit.create(OcrFactory.class);
               }
               return ocrFactory;
           }
           private HttpLoggingInterceptor httpLoggingInterceptor(){
    
               HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                   @Override
                   public void log(String message) {
                       android.util.Log.e("MyLogis :", message + "");
                   }
               });
    
               return interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
           }
       }
       ```
    
    • .addConverterFactory(ScalarsConverterFactory.create()
    • ν•œ 클래슀둜 ν•˜λ‚˜μ˜ λ ˆνŠΈλ‘œν• 객체λ₯Ό λ§Œλ“€κΈ° λ•Œλ¬Έμ— ν”„λ‘œμ νŠΈ μ „μ²΄μ—μ„œ 이 객체만 μ‚¬μš©
    • getOcrFactory()와 같은 ν•¨μˆ˜λ“€λ‘œ κΈ°λŠ₯λ³„λ‘œ μ—¬λŸ¬ μΈν„°νŽ˜μ΄μŠ€λ₯Ό λ§Œλ“€μ–΄ μ‚¬μš© κ°€λŠ₯
    • OkHttpClient λ₯Ό 톡해 HTTP μš”μ²­/응닡에 λŒ€ν•œ μƒμ„Έν•œ λ‚΄μš© 확인 κ°€λŠ₯
  5. ν•™κΈ° μ‹œκ°„ν‘œ 데이터λ₯Ό λ‹΄λŠ” Semester 클래슀 μž‘μ„±

    μ½”λ“œ 펼쳐보기
       public class Semester {
           private String major1,major2;
           private String Class1,Class2,Class3,Class4,Class5;
    
    
           public Semester(){
           }
    
           @Override
           public String toString(){
               return  "semester{" +
                       "major1='" + major1 + '\'' +
                       ", major2=" + major2 +
                       ", Class1='" + Class1 + '\'' +
                       ", Class2='" + Class2 + '\'' +
                       ", Class3='" + Class3 + '\'' +
                       ", Class4='" + Class4 + '\'' +
                       ", Class5='" + Class5 + '\'' +
                       '}';
           }
           public Semester(String major1, String major2, String Class1, String Class2, String Class3, String Class4, String Class5){
               this.major1= major1;
               this.major2 = major2;
               this.Class1 = Class1;
               this.Class2 = Class2;
               this.Class3 = Class3;
               this.Class4 = Class4;
               this.Class5 = Class5;
           }
    
           public String getClass1() {
               return Class1;
           }
    
           public void setClass1(String class1) {
               Class1 = class1;
           }
    
           public String getClass2() {
               return Class2;
           }
    
           public void setClass2(String class2) {
               Class2 = class2;
           }
    
           public String getClass3() {
               return Class3;
           }
    
           public void setClass3(String class3) {
               Class3 = class3;
           }
    
           public String getClass4() {
               return Class4;
           }
    
           public void setClass4(String class4) {
               Class4 = class4;
           }
    
           public String getClass5() {
               return Class5;
           }
    
           public void setClass5(String class5) {
               Class5 = class5;
           }
    
           public String getMajor1() {
               return major1;
           }
    
           public void setMajor1(String major1) {
               this.major1 = major1;
           }
    
           public String getMajor2() {
               return major2;
           }
    
           public void setMajor2(String major2) {
               this.major2 = major2;
           }
       }
    

    pojo μ‚¬μ΄νŠΈλ₯Ό 톡해 λΉ λ₯΄κ²Œ λ§Œλ“€μˆ˜ μžˆλ‹€

  6. μ•‘ν‹°λΉ„ν‹°μ—μ„œ Retrofit μ‚¬μš©λ°©λ²•
    1. connect ν•¨μˆ˜(GET, Res = String, Req = String )

      Call<String> res = Net.getInstance().getOcrFactory().connect("bangjinhyuk");
         res.enqueue(new Callback<String>() {
             @Override
             public void onResponse(Call<String> call, Response<String> response) {
                 if(response.isSuccessful()){
                     if(response.body() != null){
                         String success = response.body().toString();
                         Log.d("Main 톡신", response.body().toString());
                     }else{
                         Log.e("Main 톡신", "μ‹€νŒ¨ 1 response λ‚΄μš©μ΄ μ—†μŒ");
                     }
                 }else{
                     Log.e("Main 톡신", "μ‹€νŒ¨ 2 μ„œλ²„ μ—λŸ¬");
                 }
             }
      
             @Override
             public void onFailure(Call<String> call, Throwable t) {
                 Log.e("Main 톡신", "μ‹€νŒ¨ 3 톡신 μ—λŸ¬ "+t.getLocalizedMessage());
             }
         });
      
    2. connecting ν•¨μˆ˜ (GET, Res = String, Req = Map )

       Map<String, String> map = new HashMap<String, String>();
               map.put("name","bbangi");
               map.put("birth", "0103");
      
       Call<Semester> res1 = Net.getInstance().getOcrFactory().connecting(map);
       res1.enqueue(new Callback<Semester>() {
           @Override
           public void onResponse(Call<Semester> call, Response<Semester> response) {
               if(response.isSuccessful()){
                   if(response.body() != null){
                       Semester semesters = response.body();
                       Log.d("Map 톡신", semesters.toString());
                   }else{
                       Log.e("Map 톡신", "μ‹€νŒ¨ 1 response λ‚΄μš©μ΄ μ—†μŒ");
                   }
               }else{
                   Log.e("Map 톡신", "μ‹€νŒ¨ 2 μ„œλ²„ μ—λŸ¬");
               }
           }
      
           @Override
           public void onFailure(Call<Semester> call, Throwable t) {
               Log.e("Map 톡신", "μ‹€νŒ¨ 3 톡신 μ—λŸ¬ "+t.getLocalizedMessage());
      
           }
       });
      
    3. semester ν•¨μˆ˜ (POST, Res = Res_semester, Req = Req_semester)

       Req_semester req_semester = new Req_semester();
         req_semester.setSemester(new Semester(
                 "μ†Œν”„νŠΈμ›¨μ–΄ν•™κ³Ό",
                 "λ―Έλ””μ–΄ν•™κ³Ό",
                 "컴ꡬ",
                 "μ°½μ†Œμž…",
                 "κΈ°μ°½κ²½",
                 "",
                 ""
         ));
         Call<Res_semester> res2 = Net.getInstance().getOcrFactory().semester(req_semester);
         res2.enqueue(new Callback<Res_semester>() {
             @Override
             public void onResponse(Call<Res_semester> call, Response<Res_semester> response) {
                 if(response.isSuccessful()) {
                     if (response.body() != null) {
                         Res_semester res_semester = response.body();
      
      
                         Log.d("semester 톡신",res_semester.code+"");
      
                     } else {
                         Log.e("semester 톡신", "μ‹€νŒ¨ 1 response λ‚΄μš©μ΄ μ—†μŒ");
                     }
                 }else{
                     Log.e("semester 톡신", "μ‹€νŒ¨ 2 μ„œλ²„ μ—λŸ¬");
                 }
             }
      
             @Override
             public void onFailure(Call<Res_semester> call, Throwable t) {
      
                 Log.e("semester 톡신", "μ‹€νŒ¨ 3 톡신 μ—λŸ¬ "+t.getLocalizedMessage());
      
             }
         });
      
      • Req,Res 클래슀

          class Res_semester {
        
              int code; //μ„œλ²„λ‘œλΆ€ν„°μ˜ 응닡 μ½”λ“œ. 404, 500, 200 λ“±.
              String msg; //μ„œλ²„λ‘œλΆ€ν„°μ˜ 응닡 메세지.
              Semester semester; //κ³΅λΆ€ν•„μš”.
        
          }
          class Req_semester {
        
        
              Semester semester;
        
        
              public Semester getSemester() {
                  return semester;
              }
        
              public void setSemester(Semester semester) {
                  this.semester = semester;
              }
        
          }
        
    • μ„œλ²„μ—μ„œ μ˜¬λ°”λ₯Έ 값이 μ™”μ„λ•Œ response.isSuccessful() λŠ” μ°Έ

  7. μ„œλ²„μͺ½ ocr.js 파일 μž‘μ„±
    μ½”λ“œ 펼쳐보기
       var express = require('express');
       var router = express.Router();
    
    
       /* GET ocr listing. */
       router.get('/connect', function(req, res, next) {
         if(req.query.userEmail == 'bangjinhyuk'){
           res.send('connect all sucess');
         }else{
           res.send('connect little sucess');
         }
            
       });
    
       /* GET ocr listing. */
       router.get('/connecting', function(req, res, next) {
         if(req.query.name == 'bbangi' && req.query.birth == '0103'){
           res.send(JSON.stringify(
               {"major1":"μ†Œμ›¨", 
               "major2": "λ―Έλ””μ–΄", 
               "Class1":"1",
               "Class2":"2",
               "Class3":"3",
               "Class4":"4",
               "Class5":"5"}));
         }else{
           res.send('connecting little sucess');
         }
            
       });
    
       /* GET ocr listing. */
       router.post('/semester', function(req, res, next) {
         res.send('{"code":-1, "msg": "failed"}');
         // if(req.body.semester == 'bbangi' && req.query.birth == '0103' ){
         //   res.send('connecting all sucess');
         // }else{
         //   res.send('connecting little sucess');
         // }
            
       });
    
       /* GET ocr listing. */
       router.get('/', function(req, res, next) {
         // res.send(req.body.userEmail);
            
           res.send('connect');
         });
    
    
       module.exports = router;
    

λ§¨μœ„λ‘œπŸ‘†