OkHttpClient okHttpClient = new OkHttpClient.Builder()
                //  SSL 인증 과정 진행
                .hostnameVerifier (hostnameVerifier)
                //  헤더에 AUTHORIZATION 정보를 추가
                .addInterceptor (new Interceptor ()
                {
                    @Override
                    public okhttp3.Response intercept (Chain chain) throws IOException
                    {
                        Request request = chain.request ().newBuilder ().addHeader ("AUTHORIZATION", headerToken).build ();
                        return chain.proceed (request);
                    }
                })

 

 

//  통신 시 json 사용과 해당 객체로의 파싱을 위해 생성,
//  이 부분이 없을 시 IllegalArgumentException 발생 함
Gson gson = new GsonBuilder ().setLenient ().create ();

 

 

 // 사용할 Retrofit과, API를 작성해둔 인터페이스를 선언 함
Retrofit retrofit;
ApiService apiService;

retrofit = new Retrofit.Builder ()
                //  서버 주소를 추가
                .baseUrl (GlobalApplication.getGlobalApplicationContext ().getString (R.string.server_address_root))
                //  Json 사용을 위해 ConvertFactory 추가
                .addConverterFactory (GsonConverterFactory.create (gson))
                //  https 통신을 위한 SSL 인증과정과, 헤더에 인증정보를 추가한 httpClient설정
                .client (okHttpClient)
                .build ();

//  API를 사용하기 위한 서비스 생성
apiService= retrofit.create (ApiService .class);

 

 

/**
 *  ApiService 인터페이스
 *  Rest API 의 메서드들을 선언 해두는 곳 
 */
public interface ApiService
{
    /**
     *  POST 형식을 사용하며, base URL 이후 상세 URL을 작성
     *  Body 에는 UserData 를 json 형식으로 추가함
     *
     *  결과는 서버에서 클라이언트로 부터 전달받은 UserData를 가공하여
     *  다시 클라이언트로 UserData로 전달해 줌
     */
    @POST ("/SpringServer/user")
    Call<UserData> hello(@Body UserData userData);
}

 

 

 

Call<UserData> userDataCall = apiService.hello (user);

        //  비동기식 호출 사용
        userDataCall.enqueue (new Callback<UserData> ()
        {
            @Override
            public void onResponse (Call<UserData> call, Response<UserData> response)
            {
                if(response.isSuccessful ())
                {
                    //  Response 가 성공한 상태
                    userData = response.body ();
                }
                else
                {
                    //  Response 가 실패한 상태
                    //  서버와의 통신에 성공하였지만, 서버 내부 동작 중에서 잘못된 점이 확인되어,
                    //  통신에는 성공한 상태로 설정하고, Body 에 실패한 정보를 추가
                    //  ex) 서버에서 잘못된 params 를 체크하여 잘못된 정보가 있다고 return
                    try
                    {
                        String result = response.errorBody ().string ();
                        Gson gson = new Gson ();

                         /**
                         ErrorCode.Class                       
                         public class ErrorCode
                         {
                            public String code;
                            public String message;
                         }
                         */
                        ErrorCode errorCode = gson.fromJson (result, ErrorCode.class);
                    }
                    catch(Exception e)
                    {
                        e.printStackTrace ();
                    }
                }
            }

            @Override
            public void onFailure (Call<UserData> call, Throwable t)
            {
                //  Request 가 실패한 상태 ( 통신 자체, 서버의 구현 이외의 에러 발생 )
                //  ex) 통신이 불가, 서버와의 연결 실패 등               
            }
        });

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'[Android] - 개념 > Retrofit2' 카테고리의 다른 글

Retrofit2. 3. 참고 URL  (0) 2017.03.13
Retrofit2. 2.사용방법 (Retrofit 2로 HTTP 호출하기)  (0) 2017.03.12
Retrofit2. 1.기본 개념  (0) 2017.03.12
Posted by 농부지기
,

[ Retrofit2. 2.사용방법  (Retrofit 2로 HTTP 호출하기) ]

 

1. 정의

    - Retrofit은 안드로이드와 Java 애플리케이션을 위한 라이브러리로, 안전한 타입(type-safe) 방식의 HTTP 클라이언트 이다. 이번 글에서는 Retrofit 2 HTTP 클라이언트의 사용 복잡성과 앱 적용 시의 유용성을 살펴볼 예정이다.

 

 

1. 네트워크 사용을 위해서 AndroidManifest.xml 에서 Internet Permission 을 허용해야 됨

 

 <manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>

 

 

2. Retrofit을 사용하기 위해서 build.gradle 파일에 라이브러리 추가

   - Retrofit2만 적용시

 

 dependencies {
    compile 'com.squareup.retrofit2:retrofit:2.1.0'

}

 

  - Retrofit2 + gson 적용시

 

 dependencies {
    compile 'com.google.code.gson:gson:2.7'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0' 
}

 

 

 

3. 모델 클래스 만들기(데이터 그릇)

 

 public class Contributor {
 
  String login;
  String html_url;
 
  int contributions;
 
  @Override
  public String toString() {
    return login + "(" + contributions + ")";
  }
}

 

4. HTTP 통신을 하기 위한 서비스 인터페이스를 생성

 

 public interface GitHubService {
 
  @GET("repos/{owner}/{repo}/contributors")
  Call<List<Contributor>> repoContributors(
      @Path("owner") String owner
      , @Path("repo") String repo);
}

 

5. Retrofit 객체를 GitHubService 에 생성

   기본적인 Retrofit 객체 생성 형태는 아래와 같지만,

 

 public static final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://api.github.com/")
            .build();

.addConverterFactory(GsonConverterFactory.create());

는 받아오는 Json 형식의 데이터를 Java 객체 형태로 변환 또는 반대 형식으로 변환시켜주는 Gson 라이브러리를 사용해야하기 때문에 수정해야 됨.

 

 

 public interface GitHubService {
 
  @GET("repos/{owner}/{repo}/contributors")
  Call<List<Contributor>> repoContributors(
      @Path("owner") String owner
      , @Path("repo") String repo);
 
  public static final Retrofit retrofit = new Retrofit.Builder()
      .baseUrl("https://api.github.com/")
      .addConverterFactory(GsonConverterFactory.create())
      .build(); 
}

 

6. HTTP 호출

   동기적으로 HTTP 를 호출하기 위해서 인터페이스를 구현하고

   Call 호출하기 위한 형태는 아래와 같다.

 

 GitHubService gitHubService = GitHubService.retrofit.create(GitHubService.class);
 Call<List<Contributor>> call = gitHubService.repoContributors(“square”, “retrofit”);
 List<Contributor> result = call.execute().body();

 

 그러나 Android 에서는 MainThread(UI Thread) 에서 네트워크 통신을 할 수 없도록 되어 있다.
위의 형태로 돌릴 경우 아래와 같은 에러 메세지가 떨어지게 된다.

 

 02-04 19:32:55.190 1678-1678/com.example.jihoonryu.retrofit2_test E/AndroidRuntime:
 FATAL EXCEPTION: main
 Process: com.example.jihoonryu.retrofit2_test, PID: 1678
 android.os.NetworkOnMainThreadException

 

그렇기 때문에 AsyncTask 를 통해서 백그라운드 스레드에서 작동을 시켜야 한다.

 

- 동기(Synchronous)

 

new AsyncTask<Void, Void, String>() {
 
    @Override
    protected String doInBackground(Void... params) {
      GitHubService gitHubService = GitHubService.retrofit.create(GitHubService.class);
      Call<List<Contributor>> call = gitHubService.repoContributors("square", "retrofit");
     
    try {
        return call.execute().body().toString();
      } catch (IOException e) {
        e.printStackTrace();
      }
 
      return null;
    }
 
    @Override
    protected void onPostExecute(String s) {
      super.onPostExecute(s);
      TextView textView = (TextView) findViewById(R.id.textView);
      textView.setText(s);
    }
}.execute();

 

 Retrofit2 의 장점은 동기적이던 비동기적이던 구현하기 쉬움에 있다.
비동기적(Asynchronously) 으로 구현할 경우는 자체적으로 백그라운드 스레드를 타기 때문에 그냥 구현해주면 된다.

 

 -비동기(Asynchronous)

 

 

 GitHubService gitHubService = GitHubService.retrofit.create(GitHubService.class);
    Call<List<Contributor>> call = gitHubService.repoContributors("square", "retrofit");
    call.enqueue(new Callback<List<Contributor>>() {
      @Override
      public void onResponse(Call<List<Contributor>> call,
          Response<List<Contributor>> response) {
 
        TextView textView = (TextView) findViewById(R.id.textView);
        textView.setText(response.body().toString());
      }
 
      @Override
      public void onFailure(Call<List<Contributor>> call, Throwable t) {
 
      }
});

 

 

 

 

참고] http://devuryu.tistory.com/44


1. Realm / Retorift2로 HTTP 호출하기
2. Retrofit 한글 소개
3. Getting started with Retrofit 2
4. Retrofit 2.0: The biggest update yet on the best HTTP Client Library for Android

'[Android] - 개념 > Retrofit2' 카테고리의 다른 글

Retrofit2. 3. 참고 URL  (0) 2017.03.13
hanjul에 추가할 주석문장  (0) 2017.03.13
Retrofit2. 1.기본 개념  (0) 2017.03.12
Posted by 농부지기
,

[ Retrofit2. 1.기본 개념 ]

 

1. 사용이유

    - 안드로이드에서 HTTP 통신을 쉽게 할 수 있도록 해주는 라이브러리이다.

 

2. 이전 HTTP 통신 라이브러리

    - 이전 프로젝트에서는 Android Volley를 적용하여 개발하였음.

    - Volley 처음 적용시 설정과 구현을 통해 서버와의 통신을 하는데까지 복잡하고 손이 많이 간다는 느낌과  생각보다 조금 무겁다는 느낌  그리고 필요로 하는 기능보다 사용하지 않는 기능이 더 많다.

    - 그렇다고 Volley 가 안좋다는 것은 아니며 RequestQueue, NetworkImageView, DiskBasedCache를 이용하여 안정적이고 유용하게 쓸 수 있다.

 

 

Posted by 농부지기
,