본문 바로가기

ANDROID

Retrofit2 + Okhtttp3 를 이용하여 데이터를 달아보자

기존에 aQuery 라는 라이브러리를 이용하여 통신을 했었는데

 

많이 사용들하는 Retrofit를 이용한 데이터 가져오기를 구현 할라한다.

 

---------------------------------------------------------------------------------------------------

 

1.의존성 등록

1
2
3
4
5
    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
    implementation 'com.squareup.okhttp3:okhttp-urlconnection:3.0.1'
 

2.인터페이스 생성

1
2
3
4
5
public interface HttpService
{
    @GET("/디렉토리/test1.jsp/")
    Call<UserInfoApdater> getData(@Query("param1"String param1, @Query("param2"String param2);
}
 

3.통신 클래스 생성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
public class HttpConnHandler
{
 
    public static final int CONNECT_TIMEOUT = 60;
    public static final int WRITE_TIMEOUT = 60;
    public static final int READ_TIMEOUT = 60;
    private static final String SERVER_URL = "http://www.test.co.kr/";
    private static OkHttpClient client;
    private static HttpService Interface;
 
    public synchronized static HttpService getInstance() {
        if (Interface == null) {
            //통신로그를 확인하기 위한 부분
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
 
            //쿠키 메니저의 cookie policy를 변경 합니다.
            CookieManager cookieManager = new CookieManager();
            cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
 
            //OkHttpClient를 생성.
            client = configureClient(new OkHttpClient().newBuilder()) //인증서 무시
                    .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS) //연결 타임아웃 시간 셋팅
                    .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS) //쓰기 타임아웃 시간 셋팅
                    .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS) //읽기 타임아웃 시간 셋팅
                    .cookieJar(new JavaNetCookieJar(cookieManager)) //쿠키메니져 셋팅
                    .addInterceptor(httpLoggingInterceptor) //http 로그 확인
                    .build();
 
            //Retrofit 설정
            Interface = new Retrofit.Builder()
                    .baseUrl(SERVER_URL)
                    .client(client)
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) //Rxandroid를 사용하기 위해 추가(옵션 사항)
                    .addConverterFactory(GsonConverterFactory.create()) //Json Parser 추가
                    .build().create(HttpService.class); //인터페이스 연결 부분
        }
        return Interface;
    }
    
    public static OkHttpClient.Builder configureClient(final OkHttpClient.Builder builder) {
        final TrustManager[] certs = new TrustManager[]{new X509TrustManager() {
 
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException {
 
            }
 
            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException {
 
            }
 
            @Override
                return new java.security.cert.X509Certificate[0];
            }
        }};
 
        SSLContext ctx = null;
        try {
            ctx = SSLContext.getInstance("TLS");
            ctx.init(null, certs, new SecureRandom());
        } catch (final java.security.GeneralSecurityException ex) {
            ex.printStackTrace();
        }
 
        try {
            final HostnameVerifier hostnameVerifier = new HostnameVerifier() {
                @Override
                public boolean verify(final String hostname, final SSLSession session) {
                    return true;
                }
            };
 
            builder.sslSocketFactory(ctx.getSocketFactory()).hostnameVerifier(hostnameVerifier);
        } catch (final Exception e) {
            e.printStackTrace();
        }
 
        return builder;
    }
}
 
 

4. 데이터 담을 DTO 생성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class UserInfoApdater
{
    String result;
    String title;
    ArrayList<JsonResult> jsonResult;
 
    public String getTitle() {
        return title;
    }
 
    public void setTitle(String title) {
        this.title = title;
    }
 
    public String getResult()
    {
        return result;
    }
 
    public void setResult(String result)
    {
        this.result = result;
    }
 
    public ArrayList<JsonResult> getJsonResult()
    {
        return jsonResult;
    }
 
    public void setJsonResult(ArrayList<JsonResult> jsonResult)
    {
        this.jsonResult = jsonResult;
    }
}
 
 

4-1. 배열 데이터 담을 DTO 생성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class JsonResult {
 
    String name;
    String age;
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getAge() {
        return age;
    }
 
    public void setAge(String age) {
        this.age = age;
    }
 
}
 
 

 

 

 

5. 데이터 가져오기!!!!!!!!!!!!!!!!!

 

다음과 같은 데이터를 가져온다 가정하에 코드를 구성했다.

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
void getData()
    {
        try
        {
            Call<UserInfoApdater> jsonObjectCall = HttpConnAppHandler.getInstance().getData("param1""param2");
            jsonObjectCall.enqueue(new Callback<UserInfoApdater>()
            {
                @Override
                public void onResponse(Call<UserInfoApdater> call, Response<UserInfoApdater> response)
                {
                    //데이터 통신 성공 처리
                    try
                    {
                        if("Y".equals(response.body().getResult()))
                        {
                            //1.일반 JSON값 가져오기
                            String title = response.body().getTitle();
 
                            //2.JSON Araay값 가져오기
                            List<JsonResult> list = new ArrayList(response.body().getJsonResult());
                            for(JsonResult data : list)
                            {
                                String name = data.getName();
                                String age = data.getAge();
                            }
                        }
                        else
                        {
                            // 데이터 실패처리
                        }
 
                    }
                    catch (Exception e)
                    {
                        // 데이터 실패처리
                    }
                }
                @Override
                public void onFailure(Call<UserInfoApdater> call, Throwable t) {
                    // 데이터 실패처리
                }
            });
        }
        catch (Exception e)
        {
            // 데이터 실패처리
        }
    }
 

 

더 좋은 아이디어 있으면 댓글 주세요......

 

출처 : https://developer88.tistory.com/2

 

Gson + Retrofit + RxAndroid이용해 JSON파싱할 때 Nested Array 처리

파싱이란걸 하려고 보면, 저의 작은 희망과는 다르게;;; 중첩된 JSON을 많이 보게 되지요. 구글님이 만들어주신 GSON은 JSON 객체를 Java객체로 만들어줘서 코딩을 편하게 해주는데요. 중첩된 배열의 Json을 어떻..

developer88.tistory.com

출처 : https://tiii.tistory.com/11