레트로핏 사용.(java)
안드로이드 프로젝트 생성.
gradle dependencies setting.
app gradle.
dependencies {
    // 인터넷 연결 http 프로토콜
    // https://square.github.io/retrofit/
    // okhttp 를 포함하고 있다.
    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    // https://github.com/square/retrofit/tree/master/retrofit-converters/gson
    // gson 라이브러리를 포함하고 있다.
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
    // http 통신시 로그 보기위한 것.
    // https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor
    // okhttp 를 포함하고 있다.
    implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
}
레트로핏을 사용할 기본 조건은 되었고.
레트로핏으로 통신을 할수있는 인터페이스 연결할 클래스 생성.
레트로핏은 http api를 인터페이스 형태로 사용한다.
public class GithubUser {
    private String login;
    private String url;
    private String name;
    private String location;
    private String repos_url;
    public String getLogin() {
        return login;
    }
    public void setLogin(String login) {
        this.login = login;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }
    public String getRepos_url() {
        return repos_url;
    }
    public void setRepos_url(String repos_url) {
        this.repos_url = repos_url;
    }
    @Override
    public String toString() {
        return "login :" + login + ", url :" + url + ", name :" + name + ", location : " + location + ", repos_url :" + repos_url;
    }
}
public class GithubUserRepository {
    private String name;
    private String html_url;
    private String language;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getHtml_url() {
        return html_url;
    }
    public void setHtml_url(String html_url) {
        this.html_url = html_url;
    }
    public String getLanguage() {
        return language;
    }
    public void setLanguage(String language) {
        this.language = language;
    }
    @Override
    public String toString() {
        return "name : " + name + ", html_url : " + html_url + ", language : " + language;
    }
}
public interface GithubService {
    @GET("users/{user}")
    Call<GithubUser> getGithubUser(@Path("user") String userName);
    @GET("users/{user}/repos")
    Call<List<GithubUserRepository>> getGithubUserRepository(@Path("user") String userName);
}
ApiConnection 클래스 생성.
실제 통신을 담당할 retrofit 객체를 생성한다.
public class ApiConnection {
    private Retrofit retrofit;
    private final String baseUrl = "https://api.github.com";
    /**
     * 생성자.
     */
    private ApiConnection() {
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .build();
        this.retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                // 내려받는 데이터를 gson 형식으로 데이터 변환
                .addConverterFactory(GsonConverterFactory.create())
                .client(httpClient)
                .build();
    }
        /**
     * 2. 싱글턴 패턴 구현.
     */
    private static final ApiConnection INSTANCE = new ApiConnection();
    public static ApiConnection getInstance() {
        return INSTANCE;
    }
    /**
     * interface  리턴.
     */
    public GithubService getRetrofitService() {
        return retrofit.create(GithubService.class);
    }
}
    MainActivity 에서
    void connection_01() {
        Call<GithubUser> result = ApiConnection.getInstance().getRetrofitService().getGithubUser("bearkinf");
        result.enqueue(new Callback<GithubUser>() {
            @Override
            public void onResponse(Call<GithubUser> call, Response<GithubUser> response) {
                Log.w("LOG","GithubUser : " + response.body());
            }
            @Override
            public void onFailure(Call<GithubUser> call, Throwable t) {
            }
        });
    }
oncreate()에서 함수를 호출하면 깃허브에서 내용을 가져온다.
레트로핏을 이용한 통신 프로젝트에 RxJava 넣기..
라이브러리 추가.
dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:support-v4:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    //로그켓 .
    implementation 'com.github.bearkinf:AndroidLogPrintUtil_Java:1.1.1'
    // 인터페이스를 통해 인터넷 연결을 가지고 있다.
    // https://square.github.io/retrofit/
    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    // https://github.com/square/retrofit/tree/master/retrofit-converters/gson
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
    // http 통신시 로그 보기위한 것.
    // https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor
    implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
    // Rxjava 타입을 지원한다.
    // https://github.com/square/retrofit/tree/master/retrofit-adapters/rxjava2
    // 자체적으로 RxJava 라이브러리를 가지고 있다.(최신 버전은 아님.)
    // adapter-rxjava2 내부적으로 rxjava를 참조하나, 버그가 수정된 최신버전의 rxjava를 명확히 정의하여 해당 library를 사용하게 하도록한다.
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0'
    // https://github.com/ReactiveX/RxJava
    // 각각의 라이브러리가 RxJava를 참조하나 최신 라이브러리를 지정한다.
    // rxandroid 내부적으로 rxjava를 참조하나, 버그가 수정된 최신버전의 rxjava를 명확히 정의하여 해당 library를 사용하게 하도록한다.
    implementation "io.reactivex.rxjava2:rxjava:2.2.6"
    // https://github.com/ReactiveX/RxAndroid 스케줄러 관리 (쓰레드 관리
    // 자체적으로 RxJava 라이브러리를 가지고 있다.(최신 버전은 아님.)
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
}
레트로핏 인터페이스에 RxJava 추가.
public interface GithubService {
    @GET("users/{user}")
    Call<GithubUser> getGithubUser(@Path("user") String userName);
    @GET("users/{user}/repos")
    Call<List<GithubUserRepository>> getGithubUserRepository(@Path("user") String userName);
    //RxJava 용 .Observable
    @GET("users/{user}")
    Observable<GithubUser> getGithubUser2(@Path("user") String userName);
    @GET("users/{user}/repos")
    Flowable<List<GithubUserRepository>> getGithubUserRepository2(@Path("user") String userName);
}
레트로핏 객체에 RxJava 를 사용하기 위해 아답터 추가.
public class ApiConnection {
    private Retrofit retrofit;
    private final String baseUrl = "https://api.github.com";
    /**
     * 생성자.
     */
    private ApiConnection() {
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .build();
        this.retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                // 내려받는 데이터를 gson 형식으로 데이터 변환
                .addConverterFactory(GsonConverterFactory.create())
                // RxJava 를 사용하게되면 해당 아답터팩토리를 등록해야 한다.
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(httpClient)
                .build();
    }
        /**
     * 2. 싱글턴 패턴 구현.
     */
    private static final ApiConnection INSTANCE = new ApiConnection();
    public static ApiConnection getInstance() {
        return INSTANCE;
    }
    /**
     * interface  리턴.
     */
    public GithubService getRetrofitService() {
        return retrofit.create(GithubService.class);
    }
}
MainActivity에서 RxJava를 이용한 레트로핏 통신 코드 넣기.
    void connection_03() {
        /**
         * 람다식으로 사용을하려면 .
         *   compileOptions {
         *         sourceCompatibility JavaVersion.VERSION_1_8
         *         targetCompatibility JavaVersion.VERSION_1_8
         *   }
         *   넣어 주어야 한다.
         */
        LogPrintUtil.w("connection_03 start");
        ApiConnection.getInstance().getRetrofitService()
                .getGithubUser2("bearkinf")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(githubUser -> {
                            LogPrintUtil.w("Observable    Data :" + githubUser);
                        }, throwable -> {
                        }
                );
    }
oncreate()에서 함수를 호출하면 깃허브에서 내용을 가져온다.
코틀린 버전은 코틀린 탭에서. 다시 작성.
코틀린 프로잭트 생성.
레트로핏 인터페이스 생성.
interface GithubService {
    @GET("users/{user}")
    fun getGithubUser(@Path("user") userName: String): Call<GithubUser>
    @GET("users/{user}/repos")
    fun getgithubUserRepository(@Path("user") userName: String): Observable<List<GithubUserRepository>>
}
레트로핏 객체 클래스 생성.
/**스테틱 클래스 생성.*/
object ApiConnection {
    private val BASE_URL = "https://api.gitHub.com"
    private val retrofit by lazy {
        val httpClient = OkHttpClient.Builder()
            .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
            .build()
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .client(httpClient)
            .build()
    }
    val getRetrofitService = retrofit.create(GithubService::class.java)
}
MainActivity 에서 oncreate 에 함수 적용.
    private fun retrofitConnection_01() {
        val getGithubUser = ApiConnection.getRetrofitService.getGithubUser("bearkinf")
        getGithubUser.enqueue(object : Callback<GithubUser> {
            override fun onFailure(call: Call<GithubUser>, t: Throwable) {
            }
            override fun onResponse(call: Call<GithubUser>, response: Response<GithubUser>) {
                LogPrintUtil.w("response : ${response.body()}")
            }
        })
    }
    private fun retrofitConnection_02() {
        ApiConnection.getRetrofitService
            .getgithubUserRepository("bearkinf")
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                LogPrintUtil.w("RxJava : $it")
            }, {
            })
    }