본문 바로가기
Android

안드로이드 스튜디오, JAVA 실습 : 영화 API 사이트에서 데이터 가져오기

by 김마리님 2020. 7. 30.

이용하는 개념 포스팅 :

https://itstudy-mary.tistory.com/221

 

안드로이드 스튜디오, JAVA] Retrofit2를 이용하여 데이터 통신하기

https://square.github.io/retrofit/ Retrofit A type-safe HTTP client for Android and Java square.github.io 레트로핏을 이용하기 위해서는 다음과 같이 의존성을 추가로 걸어야 한다. (앱 단위의 Gradle) imp..

itstudy-mary.tistory.com

 

사용할 영화 API는 다음 페이지에서 가져온다.

https://yts.mx/api

 

API Documentation - YTS YIFY

Official YTS YIFY API documentation. YTS offers free API - an easy way to access the YIFY movies details.

yts.mx

먼저 모델을 만든다. 모델은 json으로 만들고 -> 만든 데이터를 확인하고 -> 다음 사이트를 참조하여 모델 클래스를 제작한다.

http://www.jsonschema2pojo.org/

 

먼저 값을 출력할 activity를 생성한다

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="8dp"
    tools:context=".MainActivity">

    <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/text_view_result"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#000" />

    </androidx.core.widget.NestedScrollView>

</androidx.constraintlayout.widget.ConstraintLayout>

 

 

Yts.java

package com.mary.retrofit2ex;

import com.google.gson.annotations.SerializedName;

import java.util.List;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;


@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder

public class Yts {

        private String status;
        private String statusMessage;
        private Data data;

    @lombok.Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Data {

        private Integer movieCount;
        private Integer limit;
        private Integer pageNumber;
        @SerializedName("movies")
        private List<Movie> movies = null;

        @lombok.Data
        @NoArgsConstructor
        @AllArgsConstructor
        public class Movie {

            private Integer id;
            private String url;
            private String imdbCode;
            private String title;
            private String titleEnglish;
            private String titleLong;
            private String slug;
            private Integer year;
            private Double rating;
            private Integer runtime;
            private List<String> genres = null;
            private String summary;
            private String descriptionFull;
            private String synopsis;
            private String ytTrailerCode;
            private String language;
            private String mpaRating;
            private String backgroundImage;
            private String backgroundImageOriginal;
            private String smallCoverImage;
            private String mediumCoverImage;
            private String largeCoverImage;
            private String state;
            private List<Torrent> torrents = null;

            @lombok.Data
            @AllArgsConstructor
            @NoArgsConstructor
            public class Torrent {

                private String url;
                private String hash;
                private String quality;
                private String type;
                private Integer seeds;
                private Integer peers;
                private String size;
                private Integer sizeBytes;
                private String dateUploaded;
                private Integer dateUploadedUnix;

            }
            private String dateUploaded;
            private Integer dateUploadedUnix;

        }
    }
        private Meta meta;

        @lombok.Data
        @NoArgsConstructor
        @AllArgsConstructor
        public class Meta {

            private Integer serverTime;
            private String serverTimezone;
            private Integer apiVersion;
            private String executionTime;
    }
    }

 

안드로이드와 인터넷을 연결할 인터페이스를 만든다.

 

YtsPlaceHolderApi.java

package com.mary.retrofit2ex;

import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;

public interface YtsPlaceHolderApi {
    @GET("list_movies.json")
    Call<Yts> getYts(@QueryMap Map<String,String > queryString);
}

 

이 때. GET 뒤 어노테이션 속 값은 자원 url 뒤의 값을 입력한다.

 

마지막으로 소통할 자바 코드를 작성한다.

package com.mary.retrofit2ex;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "Main_Activity";
    private TextView textViewResult;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textViewResult = findViewById(R.id.text_view_result);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://yts.mx/api/v2/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        YtsPlaceHolderApi ytsPlaceHolderApi = retrofit.create(YtsPlaceHolderApi.class);

        //쿼리스트링 만들기
        Map<String, String > queryString=new HashMap<>();
        queryString.put("sort_by","rating");
        queryString.put("page","3");

        Call<Yts> call = ytsPlaceHolderApi.getYts(queryString);

        Log.d(TAG, "onCreate: call "+ call);
        call.enqueue(new Callback<Yts>() {
            @Override
            public void onResponse(Call<Yts> call, Response<Yts> response) {
                if (!response.isSuccessful()) {
                    Log.d(TAG, "onResponse: 여기가 오류인가?");
                    textViewResult.setText("Code: " + response.code());
                    return;
                }
                Yts yts = response.body();
                for(Yts.Data.Movie movie:yts.getData().getMovies()) {
                    String content = "";
                    content += "title: " + movie.getTitle()+ "\n";
                    content += "Rate: " + movie.getRating()+ "\n";
                    content += "Rate: " + movie.getSummary()+ "\n\n";
                    textViewResult.append(content);
                }
                }
            @Override
            public void onFailure(Call<Yts> call, Throwable t) {
                Log.d(TAG, "onFailure: "+t);
            }
        });
    }
}

 

결과 화면:

반응형