반응형
https://codinginflow.com/tutorials/android/retrofit/part-1-simple-get-request
https://square.github.io/retrofit/
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.lwm.retrofit2ex01">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<?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>
JsonPlaceHolderApi.java
package com.lwm.retrofit2ex01;
import java.util.Map;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.QueryMap;
public interface JsonPlaceHolderApi {
@GET("list_movies.json")
Call<Yts> getMovies(@QueryMap Map<String, String> queryString);
}
MainActivity.java
package com.lwm.retrofit2ex01;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.util.HashMap;
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 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();
JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
//쿼리 스트링 만들기
Map<String, String> queryString = new HashMap<>();
queryString.put("sort_by", "rating");
queryString.put("page", "3");
Call<Yts> call = jsonPlaceHolderApi.getMovies(queryString);
call.enqueue(new Callback<Yts>() {
@Override
public void onResponse(Call<Yts> call, Response<Yts> response) {
if (!response.isSuccessful()) {
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 += "YEAR: " + movie.getYear() + "\n";
content += "RATING: " + movie.getRating() + "\n";
content += "SUMMARY: " + movie.getSummary() + "\n\n";
textViewResult.append(content);
}
}
@Override
public void onFailure(Call<Yts> call, Throwable t) {
textViewResult.setText(t.getMessage());
}
});
}
}
Yts.java
package com.lwm.retrofit2ex01;
import java.util.List;
import lombok.Data;
@Data
public class Yts {
private String status;
private String statusMessage;
private Data data;
private Meta meta;
@lombok.Data
public class Data {
private Integer movieCount;
private Integer limit;
private Integer pageNumber;
private List<Movie> movies = null;
@lombok.Data
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 String dateUploaded;
private Integer dateUploadedUnix;
}
}
@lombok.Data
public class Meta {
private Integer serverTime;
private String serverTimezone;
private Integer apiVersion;
private String executionTime;
}
}
Post.java
package com.lwm.retrofit2ex01;
import com.google.gson.annotations.SerializedName;
public class Post {
private int userId;
private int id;
private String password;
@SerializedName("body")
private String text;
public int getUserId() {
return userId;
}
public int getId() {
return id;
}
public String getPassword() {
return password;
}
public String getText() {
return text;
}
}
build.gradle(:app)
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "30.0.0"
defaultConfig {
applicationId "com.lwm.retrofit2ex01"
minSdkVersion 21
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation group: 'com.squareup.retrofit2', name: 'converter-gson', version: '2.3.0'
compileOnly 'org.projectlombok:lombok:1.18.12'
annotationProcessor 'org.projectlombok:lombok:1.18.12'
}
반응형
'Android' 카테고리의 다른 글
Android / 간단한 계산기 앱 만들기 (0) | 2020.07.22 |
---|---|
Android / 버튼 클릭시 숫자가 증감하는 로직 (2) | 2020.07.22 |
Android/ ProgressBar (0) | 2020.07.22 |
Android/ AppCompat위젯으로 버튼 생성하고 클릭 이벤트 주기 (0) | 2020.07.22 |
Android / ScrollView (0) | 2020.07.21 |