[Android Studio]서버와 연결을 하기 위한 기본 구성 - retorifit2, Gson, okttp3 준비하기

|

gradle에 다음을 추가한다.

implementation 'com.squareup.retrofit2:retrofit:2.3.0' implementation 'com.squareup.retrofit2:converter-gson:2.3.0' implementation 'com.squareup.okhttp3:logging-interceptor:3.3.1' implementation 'com.squareup.okhttp3:okhttp:3.8.1'

remote란 패키지 하나를 만들자.
그리고 그 안에 다음을 그냥 붙여 넣는다.

// ServiceGenerator.java import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.koreanlab.xxx.BuildConfig; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by Chanj on 11/06/2018. */ public class ServiceGenerator { public static <S> S createService(Class<S> serviceClass){ HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); if(BuildConfig.DEBUG){ loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); }else{ loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE); } OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); httpClient.addInterceptor(loggingInterceptor); Gson gson = new GsonBuilder() .setLenient() .create(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(RemoteService.BASE_URL) .addConverterFactory(GsonConverterFactory.create(gson)) .build(); return retrofit.create(serviceClass); } }

위의 소스는 변경할 게 없다.

아래의 소스만 서버와 통신할 때 수정해주면된다.

// RemoteService.java (인터페이스다) import java.util.ArrayList; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.POST; /** * Created by Chanj on 11/06/2018. */ public interface RemoteService { String BASE_URL = "http://aaa.bbb.ccc.ddd:pppp"; @POST("/search/article") Call<ArrayList<ArticleItem>> selectArticle(@Body SearchItem searchItem); @POST("/write/article") Call<Integer> insertArticle(@Body ArticleItem searchItem); }

어노테이션에 대해서는 따로 검색해보길 바란다.

서버와 통신이 되려면 Activity와 remote가 연결이 되어야 하는데 다음과 같이 처리한다.

private void getList(SearchItem searchItem) { RemoteService remoteService = ServiceGenerator.createService(RemoteService.class); Call<ArrayList<ArticleItem>> call = remoteService.selectArticle(searchItem); call.enqueue(new Callback<ArrayList<ArticleItem>>() { @Override public void onResponse(Call<ArrayList<ArticleItem>> call, Response<ArrayList<ArticleItem>> response) { ArrayList<ArticleItem> resultItems = response.body(); if (response.isSuccessful() && resultItems != null) { Log.d(TAG, resultItems.toString()); searchListAdapter = new SearchAdapter(getApplicationContext(), resultItems); listView.setAdapter(searchListAdapter); } Log.d(TAG, "Got results from server successfully!!!"); } @Override public void onFailure(Call<ArrayList<ArticleItem>> call, Throwable t) { Log.d(TAG, "Got no results. :("); Log.d(TAG, t.toString()); } }); }

여기서 Articleitem은 필자가 직접 만든 객체다. 나머지는 비슷한 형식으로 처리하면 된다.


And