이용하는 개념 포스팅 :
https://itstudy-mary.tistory.com/221
사용할 영화 API는 다음 페이지에서 가져온다.
먼저 모델을 만든다. 모델은 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);
}
});
}
}
결과 화면:
반응형
'Android' 카테고리의 다른 글
안드로이드 스튜디오, JAVA] 실습 : 레트로핏, 리사이클러뷰, 피카소를 이용한 영화 앱 만들기. (1) | 2020.07.31 |
---|---|
Android Studio, JAVA] 피카소, Glide 라이브러리 (0) | 2020.07.31 |
안드로이드 스튜디오, JAVA] Retrofit2를 이용하여 데이터 통신하기 (0) | 2020.07.29 |
안드로이드 스튜디오, JAVA] 스레드 (0) | 2020.07.28 |
실습 : 리사이클러뷰를 이용한 SNS화면 구현 (0) | 2020.07.23 |