코리아 IT아카데미/android

14일차 | 레트로핏 사용 (http 통신을 할 수 있도록 도와주는)

Sharon kim 2022. 3. 4. 17:53

?mode=LSD&mid=shm&sid1=104&oid=052&aid=0001709207

{
"cds" :"news_media_PC"
}
사이트
https://jsonplaceholder.typicode.com/
retrofit2 https://square.github.io/retrofit/
https://www.jsonschema2pojo.org/
https://www.data.go.kr/index.do
네트워크 통신 받기

 

jsonschema2pojo

Reference properties For each property present in the 'properties' definition, we add a property to a given Java class according to the JavaBeans spec. A private field is added to the parent class, along with accompanying accessor methods (getter and sette

www.jsonschema2pojo.org

 

 

공공데이터 포털

국가에서 보유하고 있는 다양한 데이터를『공공데이터의 제공 및 이용 활성화에 관한 법률(제11956호)』에 따라 개방하여 국민들이 보다 쉽고 용이하게 공유•활용할 수 있도록 공공데이터(Datase

www.data.go.kr

 

Retrofit

A type-safe HTTP client for Android and Java

square.github.io

 

JSONPlaceholder - Free Fake REST API

{JSON} Placeholder Free fake API for testing and prototyping. Powered by JSON Server + LowDB. Tested with XV. As of Oct 2021, serving ~1.7 billion requests each month.

jsonplaceholder.typicode.com

 

코드 추가

<uses-permission android:name="android.permission.INTERNET" />
def retrofit_version ="2.9.0"

dependencies {

     ...

    // Retrofit 라이브러리
    implementation "com.squareup.retrofit2:retrofit:$retrofit_version"
    // Gson 변환기 라이브러리
    implementation "com.squareup.retrofit2:converter-gson:$retrofit_version"
}

 

models>common>Address

package com.example.myretrofit2_v2.models.common;

public class Address {
        String street;
        String city;
        String suite;
        String zipcode;
        Geo geo;
}

models>common>Company

package com.example.myretrofit2_v2.models.common;

public class Company{
    String name;
    String catchPhrase;
    String bs;
}

models>common>Geo

package com.example.myretrofit2_v2.models.common;

public class Geo{
    String lat;
    String lng;
}

models>request>ReqPost

package com.example.myretrofit2_v2.models.request;

public class ReqPost {

    private int id;
    private String title;
    private String body;
    private  int userId;

    public ReqPost(String title, String body, int userId) {
        this.title = title;
        this.body = body;
        this.userId = userId;
    }
    //생성자 오버로딩 put
    public ReqPost(int id, String title, String body, int userId) {
        this.id = id;
        this.title = title;
        this.body = body;
        this.userId = userId;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

}

models>response>ResPost

package com.example.myretrofit2_v2.models.response;

public class ResPost {
    private int id;
    private String title;
    private String body;
    private  int userId;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    @Override
    public String toString() {
        return "RePost{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", body='" + body + '\'' +
                ", userId=" + userId +
                '}';
    }
}

models>response>ResPost

package com.example.myretrofit2_v2;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.myretrofit2_v2.models.request.ReqPost;
import com.example.myretrofit2_v2.models.response.ResPost;
import com.example.myretrofit2_v2.repository.PostService;

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 = MainActivity.class.getName();

    private Button button1;
    private Button button2;
    private Button button3;
    private Button button4;
    private Retrofit retrofit;
    private PostService service;
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initData();
        addEventListener();
    }

    private void addEventListener() {
        button1.setOnClickListener(v -> {
            // getPost
            requestPost();
        });
        button2.setOnClickListener(v -> {
            // createPost
            savePost();
        });
        button3.setOnClickListener(v -> {
            updatePost();
        });
        button4.setOnClickListener(v -> {
            deletePost();
        });
    }

    private void deletePost() {
        service.deletePost(3).enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                Log.d(TAG, "상태코드 : " + response.code());
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {

            }
        });
    }

    private void updatePost() {
        // putPost
        ReqPost requestPost = new ReqPost(100, "수정 타이틀", "수정 내용", 3);
        service.putPost(3, requestPost).enqueue(new Callback<ResPost>() {
            @Override
            public void onResponse(Call<ResPost> call, Response<ResPost> response) {
                Log.d(TAG, "상태 코드 " + response.code());
                Log.d(TAG, "message : " + response.message());
                if (response.isSuccessful()) {
                    ResPost resPost = response.body();
                    Log.d(TAG, "응답결과 : " + resPost.toString());
                }
            }

            @Override
            public void onFailure(Call<ResPost> call, Throwable t) {

            }
        });
    }



    private void savePost() {
        service.createPost(new ReqPost("타이틀", "내용", 3)).enqueue(new Callback<ResPost>() {
            @Override
            public void onResponse(Call<ResPost> call, Response<ResPost> response) {
                Log.d(TAG, "코드 : " + response.code());
                if (response.isSuccessful()) {
                    Log.d(TAG, "응답 결과 : " + response.body());
                    ResPost result = response.body();
                    Log.d(TAG, "result : " + result.getTitle());
                }
            }

            @Override
            public void onFailure(Call<ResPost> call, Throwable t) {

            }
        });
    }

    private void requestPost() {
        service.getPost(10).enqueue(new Callback<ResPost>() {
            @Override
            public void onResponse(Call<ResPost> call, Response<ResPost> response) {
                // 성공
                Log.d(TAG, "상태코드 : " + response.code());
                Log.d(TAG, "메세지 : " + response.message());
                Log.d(TAG, "응답 헤더 : " + response.headers());

                if (response.isSuccessful()) {
                    Log.d(TAG, "응답 결과 : " + response.body());
                    ResPost result = response.body();
                    Log.d(TAG, "result : " + result.getTitle());

                    textView.setText(result.getTitle());
                    textView.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onFailure(Call<ResPost> call, Throwable t) {
                Log.d(TAG, t.getMessage() + "  < --- 실패 ");
            }
        });
    }

    private void initData() {
        button1 = findViewById(R.id.button1);
        button2 = findViewById(R.id.button2);
        button3 = findViewById(R.id.button3);
        button4 = findViewById(R.id.button4);
        textView = findViewById(R.id.postTitleTextView);

        retrofit = new Retrofit.Builder()
                .baseUrl("https://jsonplaceholder.typicode.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        service = retrofit.create(PostService.class);

    }

}

models>Temp

package com.example.myretrofit2_v2.models;
//{
//        "id" : 10,
//        "acount" : {
//        "name" : "홍길동",
//        "email" : "a@naver.com"
//        }
//
//        }
public class Temp {
    private int id;
    private Account account;

}

class Account{
    private String name;
    private String email;
}

models>User

package com.example.myretrofit2_v2.models;


import com.example.myretrofit2_v2.models.common.Address;
import com.example.myretrofit2_v2.models.common.Company;


/*
* {
    "id": 9,
    "name": "Glenna Reichert",
    "username": "Delphine",
    "email": "Chaim_McDermott@dana.io",
    "address": {
      "street": "Dayna Park",
      "suite": "Suite 449",
      "city": "Bartholomebury",
      "zipcode": "76495-3109",
      "geo": {
        "lat": "24.6463",
        "lng": "-168.8889"
      }
    },
    "phone": "(775)976-6794 x41206",
    "website": "conrad.com",
    "company": {
      "name": "Yost and Sons",
      "catchPhrase": "Switchable contextually-based project",
      "bs": "aggregate real-time technologies"
    }
* */
public class User {

    int id;
    String name;
    String username;
    String email;
    Address address;
    String phone;
    String website;
    Company company;

}

models2>Address

package com.example.myretrofit2_v2.models2;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Address {

    @SerializedName("street")
    @Expose
    private String street;

    @SerializedName("suite")
    @Expose
    private String suite;

    @SerializedName("city")
    @Expose
    private String city;

    @SerializedName("zipcode")
    @Expose
    private String zipcode;

    @SerializedName("geo")
    @Expose
    private Geo geo;

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getSuite() {
        return suite;
    }

    public void setSuite(String suite) {
        this.suite = suite;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getZipcode() {
        return zipcode;
    }

    public void setZipcode(String zipcode) {
        this.zipcode = zipcode;
    }

    public Geo getGeo() {
        return geo;
    }

    public void setGeo(Geo geo) {
        this.geo = geo;
    }

}

models2>Company

package com.example.myretrofit2_v2.models2;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Company {

    @SerializedName("name")
    @Expose
    private String name;

    @SerializedName("catchPhrase")
    @Expose
    private String catchPhrase;

    @SerializedName("bs")
    @Expose
    private String bs;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCatchPhrase() {
        return catchPhrase;
    }

    public void setCatchPhrase(String catchPhrase) {
        this.catchPhrase = catchPhrase;
    }

    public String getBs() {
        return bs;
    }

    public void setBs(String bs) {
        this.bs = bs;
    }

}

models2>Geo

package com.example.myretrofit2_v2.models2;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Geo {
    //스네이크 케이스 phone_number
    //카멜 케이스
    @SerializedName("lat")
    @Expose
    private String lat;

    @SerializedName("lng")
    @Expose
    private String lng;

    public String getLat() {
        return lat;
    }

    public void setLat(String lat) {
        this.lat = lat;
    }

    public String getLng() {
        return lng;
    }

    public void setLng(String lng) {
        this.lng = lng;
    }

}

models2>User

package com.example.myretrofit2_v2.models2;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class User {

    @SerializedName("id")
    @Expose
    private Integer id;

    @SerializedName("name")
    @Expose
    private String name;

    @SerializedName("username")
    @Expose
    private String username;

    @SerializedName("email")
    @Expose
    private String email;

    @SerializedName("address")
    @Expose
    private Address address;

    @SerializedName("phone")
    @Expose
    private String phone;

    @SerializedName("website")
    @Expose
    private String website;

    @SerializedName("company")
    @Expose
    private Company company;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getWebsite() {
        return website;
    }

    public void setWebsite(String website) {
        this.website = website;
    }

    public Company getCompany() {
        return company;
    }

    public void setCompany(Company company) {
        this.company = company;
    }

}

repository>PostService.interface

package com.example.myretrofit2_v2.repository;

import com.example.myretrofit2_v2.models.request.ReqPost;
import com.example.myretrofit2_v2.models.response.ResPost;

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

import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.Field;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;

/*
* REST API
* GET, POST, PUT, DELETE
* */
public interface PostService {
    @GET("posts/{id}")
    Call<ResPost> getPost(@Path("id") int id);

    @GET("posts")
    Call<List<ResPost>> getPostList();

    //@FieldMap HashMap<String, Object>
    //@Field('title') String title
    //@Body ReqPost
//    @POST("posts")
//    Call<ResPost> createPostMap(@FieldMap HashMap<String, Object> reqData);
//
//    @FormUrlEncoded
//    @POST("posts")
//    Call<ResPost> createPostField(@Field("title") String title,
//                                                @Field("body") String body, @Field("userId") int userId);

    @POST("posts")
    Call<ResPost> createPost(@Body ReqPost reqPost);

    @PUT("posts/{id}")
    Call<ResPost> putPost(@Path("id") int id, @Body ReqPost reqPost);

    @DELETE("posts/{id}")
    Call<Void> deletePost(@Path("id") int id);

    @FormUrlEncoded
    @GET("posts")
    Call<List<ResPost>> searchByUserId(@Field("userId") int userId);

}

MainActivity

package com.example.myretrofit2_v2;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.myretrofit2_v2.models.request.ReqPost;
import com.example.myretrofit2_v2.models.response.ResPost;
import com.example.myretrofit2_v2.repository.PostService;

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 = MainActivity.class.getName();

    private Button button1;
    private Button button2;
    private Button button3;
    private Button button4;
    private Retrofit retrofit;
    private PostService service;
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initData();
        addEventListener();
    }

    private void addEventListener() {
        button1.setOnClickListener(v -> {
            // getPost
            requestPost();
        });
        button2.setOnClickListener(v -> {
            // createPost
            savePost();
        });
        button3.setOnClickListener(v -> {
            updatePost();
        });
        button4.setOnClickListener(v -> {
            deletePost();
        });
    }

    private void deletePost() {
        service.deletePost(3).enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                Log.d(TAG, "상태코드 : " + response.code());
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {

            }
        });
    }

    private void updatePost() {
        // putPost
        ReqPost requestPost = new ReqPost(100, "수정 타이틀", "수정 내용", 3);
        service.putPost(3, requestPost).enqueue(new Callback<ResPost>() {
            @Override
            public void onResponse(Call<ResPost> call, Response<ResPost> response) {
                Log.d(TAG, "상태 코드 " + response.code());
                Log.d(TAG, "message : " + response.message());
                if (response.isSuccessful()) {
                    ResPost resPost = response.body();
                    Log.d(TAG, "응답결과 : " + resPost.toString());
                }
            }

            @Override
            public void onFailure(Call<ResPost> call, Throwable t) {

            }
        });
    }



    private void savePost() {
        service.createPost(new ReqPost("타이틀", "내용", 3)).enqueue(new Callback<ResPost>() {
            @Override
            public void onResponse(Call<ResPost> call, Response<ResPost> response) {
                Log.d(TAG, "코드 : " + response.code());
                if (response.isSuccessful()) {
                    Log.d(TAG, "응답 결과 : " + response.body());
                    ResPost result = response.body();
                    Log.d(TAG, "result : " + result.getTitle());
                }
            }

            @Override
            public void onFailure(Call<ResPost> call, Throwable t) {

            }
        });
    }

    private void requestPost() {
        service.getPost(10).enqueue(new Callback<ResPost>() {
            @Override
            public void onResponse(Call<ResPost> call, Response<ResPost> response) {
                // 성공
                Log.d(TAG, "상태코드 : " + response.code());
                Log.d(TAG, "메세지 : " + response.message());
                Log.d(TAG, "응답 헤더 : " + response.headers());

                if (response.isSuccessful()) {
                    Log.d(TAG, "응답 결과 : " + response.body());
                    ResPost result = response.body();
                    Log.d(TAG, "result : " + result.getTitle());

                    textView.setText(result.getTitle());
                    textView.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onFailure(Call<ResPost> call, Throwable t) {
                Log.d(TAG, t.getMessage() + "  < --- 실패 ");
            }
        });
    }

    private void initData() {
        button1 = findViewById(R.id.button1);
        button2 = findViewById(R.id.button2);
        button3 = findViewById(R.id.button3);
        button4 = findViewById(R.id.button4);
        textView = findViewById(R.id.postTitleTextView);

        retrofit = new Retrofit.Builder()
                .baseUrl("https://jsonplaceholder.typicode.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        service = retrofit.create(PostService.class);

    }

}

SubActivity

package com.example.myretrofit2_v2;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class SubActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sub);
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context=".MainActivity">

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="button1" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="button2" />

        <Button
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="button3" />

        <Button
            android:id="@+id/button4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="button4" />

        <TextView
            android:id="@+id/postTitleTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Title"
            android:textColor="@color/purple_200"
            android:textSize="30dp"
            android:visibility="gone" />

</LinearLayout>

activity_sub.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"
    tools:context=".SubActivity">

</androidx.constraintlayout.widget.ConstraintLayout>