'2020/07/25'에 해당되는 글 1건

728x90

Retrofit2 라이브러리 Java 버전 코딩을 Kotlin 으로 변환해서 이용하는 법을 적어둔다.

Android Studio 에서 Java 파일 Kotlin 파일로 변환하는 기능을 이용하여 변환하고 나서 에러가 나는 부분을 수정하면 대부분 해결이 된다.

static 은 object 파일로 변환을 해버리는데, 여기서는 companion object 를 사용해서 수동 변환을 했다.


public class RetrofitAPI {
    private static Retrofit retrofit = null;

    public static Retrofit getClient() {
        retrofit = new Retrofit.Builder()
                .baseUrl(Value.IPADDRESS)
                .addConverterFactory(GsonConverterFactory.create())
                .client(createOkHttpClient())
                .build();

        return retrofit;
    }

    private static OkHttpClient createOkHttpClient() {
        // 네트워크 통신 로그(서버로 보내는 파라미터 및 받는 파라미터) 보기
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        builder.addInterceptor(interceptor);
        return builder.build();
    }
}

class RetrofitAPI {

    companion object{
        private var retrofit: Retrofit? = null

        fun getClient(): Retrofit? {
            retrofit = Retrofit.Builder()
                .baseUrl(Value.IPADDRESS)
                .addConverterFactory(GsonConverterFactory.create())
                .client(createOkHttpClient())
                .build()
            return retrofit
        }

        private fun createOkHttpClient(): OkHttpClient? {
            // 네트워크 통신 로그(서버로 보내는 파라미터 및 받는 파라미터) 보기
            val builder = OkHttpClient.Builder()
            val interceptor =
                HttpLoggingInterceptor()
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
            builder.addInterceptor(interceptor)
            return builder.build()
        }
    }

}


public interface RemoteService {// 서버에 호출할 메소드를 선언하는 인터페이스
    // POST 방식으로 데이터를 주고 받을 때 넘기는 변수는 Field 라고 해야 한다.
    @FormUrlEncoded
    @POST(RetrofitUrl.URL_LOGIN)
    Call<LoginResult> Login(
            @Field("userid") String userId,
            @Field("userpw") String userPw,
            @Field("token") String token,
            @Field("keyword") String keyword,
            @Field("mfoneNO") String mfoneNO,
            @Field("uuid") String uuid
    );
}

interface RemoteService { // 서버에 호출할 메소드를 선언하는 인터페이스
    // POST 방식으로 데이터를 주고 받을 때 넘기는 변수는 Field 라고 해야 한다.
    @FormUrlEncoded
    @POST(RetrofitUrl.URL_LOGIN)
    fun Login(
        @Field("userid") userId: String,
        @Field("userpw") userPw: String,
        @Field("token") token: String,
        @Field("keyword") keyword: String,
        @Field("mfoneNO") mfoneNO: String,
        @Field("uuid") uuid: String
    ): Call<LoginResult>
}



로그인 예제 변환

void AutoLoginProgress() { // 자동 로그인 체크 검사
    //Log.e("AutoLogin", "Auto Login Stage.");
    pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
    userID = pref.getString("userid", "");
    userPW = pref.getString("userpw", "");
    String keyword = Value.encrypt(Value.URLkey());
    String mfoneNO = Value.encrypt(getPhoneNumber());
    uID = Settings.Secure.getString(getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);

    if (userID != null && !userID.isEmpty() && userPW != null && !userPW.isEmpty()) {
        mloginService = RetrofitAPI.getClient().create(RemoteService.class);
        mloginService.Login(Value.encrypt(userID), Value.encrypt(userPW),"", keyword, mfoneNO, Value.encrypt(uID))
                .enqueue(new Callback<LoginResult>() {
                    @Override
                    public void onResponse(Call<LoginResult> call, Response<LoginResult> response) {
                        // 네트워크 통신 성공
                        LoginResult result = response.body();
                        if(result.getResult().contains("success")){

                            Log.e("Intor UserName",result.getUserinfo().getUsername());

                            Intent intent = new Intent(Intro.this, MapViewActivity.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
                            startActivity(intent);
                            finish();

                        } else {
                            if(result.getResult().contains("로그인 에러")){
                                startActivity(new Intent(Intro.this, LoginActivity.class));
                                finish();
                            } else {
                                Utils.showAlert(Intro.this,result.getResult(),result.getMessage());
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<LoginResult> call, Throwable t) {

                    }
                });

    } else {
        startActivity(new Intent(getApplication(), LoginActivity.class));
        finish();
    }

}


fun AutoLoginProgress() { // 자동 로그인 체크 검사
     //Log.e("AutoLogin", "Auto Login Stage.");
     pref = getSharedPreferences("pref", Activity.MODE_PRIVATE)
     userID = pref?.getString("userid", "")
     userPW = pref?.getString("userpw", "")
     val keyword = Value.encrypt(Value.URLkey())
     val mfoneNO = Value.encrypt(phoneNumber)
     uID = Settings.Secure.getString(applicationContext.contentResolver,Settings.Secure.ANDROID_ID)
     if (userID != null && !userID!!.isEmpty() && userPW != null && !userPW!!.isEmpty()) {
         mloginService = RetrofitAPI.getClient()!!.create(RemoteService::class.java)
         mloginService!!.Login(Value.encrypt(userID), Value.encrypt(userPW),"", keyword, mfoneNO,Value.encrypt(uID))
             ?.enqueue(object : Callback<LoginResult> {
                 override fun onResponse(
                     call: Call<LoginResult>,
                     response: Response<LoginResult>
                 ) {
                     // 네트워크 통신 성공
                     val result = response.body()
                     if (result!!.result.contains("success")) {
                         Log.e("Intor UserName", result.userinfo!!.username)
                         val intent = Intent(this@Intro, MapViewActivity::class.java)
                         intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NO_HISTORY)
                         startActivity(intent)
                         finish()
                     } else {
                         if (result.result.contains("로그인 에러")) {
                             startActivity(Intent(this@Intro,LoginActivity::class.java))
                             finish()
                         } else {
                             Utils.showAlert(this@Intro,result.result,result.message)
                         }
                     }
                 }

                 override fun onFailure(
                     call: Call<LoginResult?>,
                     t: Throwable
                 ) {
                 }
             })
     } else {
         startActivity(Intent(application,LoginActivity::class.java))
         finish()
     }
 }


블로그 이미지

Link2Me

,