본문 바로가기

안드로이드

Retrofit


retrofit 
    : A type-safe HTTP client for Android and Java  << retrofit 페이지를 접속하게 되면 최상단에 보이는 문구로서 java용 HTTP api !!

    ** java 7 이상 android 2.3 이상에서 적용 가능

-----------------------------------------------  사용 방법 ----------------------------------------------------------------------------------------

1. Gradle
    implementation 'com.squareup.retrofit2:retrofit:2.4.0'     << retrofit 추가
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'    << return 타입을 Gson 형태(json)로 받기 위해 추가
    위 사항 변경 후 sync now 클릭하여 적용

2. 권한 부여
    2-1 인터넷 권한 부여
          manifests/AndroidManifest.xml 안에 아래 코드 추가
     <uses-permission android:name="android.permission.INTERNET" />
    2-2 개발시 local 권한부여
         retrofit 에서 baseUrl 설정시 http로 설정하게 되면 
        "CLEARTEXT communication to xxx.xxx.xxx.xxx not permitted by network security policy" 라는 오류         메시지를 출력한다. 
         이때 http를 https로 바꿔서 호출하던가 아래의 코드를 입력

         2-2-1. res/xml/network_security_config.xml 에 추가
              <?xml version="1.0" encoding="utf-8"?>
                 <network-security-config>
                     <domain-config cleartextTrafficPermitted="true">
                     <domain includeSubdomains="true">api.xxx.com</domain>
                 </domain-config>
             </network-security-config>

          2-2-2. manifests/AndroidManifest.xml 에 추가
             <application
                 ...
                 android:networkSecurityConfig="@xml/network_security_config">

3. Retrofit 생성    
     Retrofit retrofit = new Retrofit.Builder()
         .baseUrl("https://api.github.com")
         .addConverterFactory(GsonConverterFactory.create())
         .build();

4. Interface 생성
    인터페이스를 생성하고 사용자 정의 코드 추가
    @GET("/login")                                                                                            << '/login' 경로로 GET 방식 호출 
     Call<loginModel> login(@QueryMap Map<StringString> userInfo);     << 제너릭을 이용하여 사용자 정의 model 형식으로 데이터 호출 및 리턴

5. model 생성
    retrofit 통신시 사용되는 model class 생성
         
     public class loginModel {
    private String userId;
    private String password;
    private boolean result;

     public String getUserId() {
    return userId;
     }

    public void setUserId(String userId) {
    this.userId = userId;
    }

     public String getPassword() {
    return password;
    }

     public void setPassword(String password) {
    this.password = password;
    }

     public boolean isResult() {
    return result;
    }

     public void setResult(boolean result) {
    this.result = result;
    }
     }
6. client 
    실질적으로 호출하는 부분
     Connect connect = new Connect();
     Map<String, String> userInfo = new HashMap<String, String>();
     userInfo.put("userId", userId);
     userInfo.put("password", password);
     Call<loginModel> loginRequest = connect.getLogin().login(userInfo);
     loginRequest.enqueue(new Callback<loginModel>() {
    @Override
    public void onResponse(Call<loginModel> call, Response<loginModel> response) {
    Log.e("success", String.valueOf(response.code()));
    }
     @Override
    public void onFailure(Call<loginModel> call, Throwable t) {
    Log.e("fail", t.toString());
    }
     });