Retrofit 샘플 소스

업데이트:

Retrifit

작성중

Usage

MainActivity에서는 Retrofit으로 https://api.github.com/users/ 형태(GitHubService)로 값을 받을 수 있게 한다. 이 상태에서 https://api.github.com/users/개인깃헙아이디를 enqueue에 넣으면, avatar_url을 return 받을 수 있다.

MainActivity.java

package com.exam.retrofit;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.exam.retrofit.api.GitHubService;
import com.exam.retrofit.api.model.GithubOwner;
import com.exam.retrofit.databinding.ActivityMainBinding;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding mainBinding;
    private GitHubService gitHubService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // https://api.github.com/users/peterkimlab
        mainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);

        gitHubService = new Retrofit.Builder()
                .baseUrl("https://api.github.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(GitHubService.class);

        mainBinding.getBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getOwnerData();
            }
        });
    }

    public void getOwnerData() {
        Call<GithubOwner> call = gitHubService.getRepo("peterkimlab");

        call.enqueue(new Callback<GithubOwner>() {
            @Override
            public void onResponse(Call<GithubOwner> call, Response<GithubOwner> response) {
                if (response.isSuccessful() && response.body() != null) {
                    mainBinding.resultTV.setText("Response Code : " + response.body().avatarUrl);
                }
            }

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

            }
        });
    }
}


github url로 통신할때, 개인깃헙아이디를 파라미터로 받어, GithubOwner type으로 return 하는 interface.

GitHubService.java

package com.exam.retrofit.api;

import com.exam.retrofit.api.model.GithubOwner;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;

public interface GitHubService {

    @GET("/users/{anything}") //https://api.github.com/users/peterkimlab
    Call<GithubOwner> getRepo(@Path("anything") String id);
}

GithubOwner.java

package com.exam.retrofit.api.model;

import com.google.gson.annotations.SerializedName;

public class GithubOwner {

    public final String login;

    @SerializedName("avatar_url")
    public final String avatarUrl;

    public GithubOwner(String login, String avatarUrl) {
        this.login = login;
        this.avatarUrl = avatarUrl;
    }
}

build.gradle(Module:app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.exam.retrofit"
        minSdkVersion 21
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    dataBinding {
        enabled = true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:25.3.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    compile 'com.google.code.gson:gson:2.2.4'
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'
    testImplementation 'junit:junit:4.12'
}

Output

참조 된 소스는, 아래의 뷰 구성이 가능 합니다. 작성중

source

전체 소스 : GitHub

카테고리:

업데이트: