본문 바로가기
프로그램/Android

[Retrofit2] GET, POST 로 API 호출해서 JSON 데이터 받아오기

by 로드러너 2021. 2. 22.
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

[ build.grade (Module) ]

 

    dependencies {

        implementation 'com.squareup.retrofit2:retrofit:2.6.0'

        implementation 'com.squareup.retrofit2.converter-gson:2.6.0'

    }

 

 

[ AndroidManifest.xml ]

 

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>

 

    <application

           ...

           android:networkSecurityConfig="@xml/network_security_config"

           ...>

 

 

[ res/xml/network_security_config ]

 

    <?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
        <base-config cleartextTrafficPermitted="true"></base-config>
    </network-security-config>

 

 

[ Result.java ]

 

    public class Result {

        private String code;

        private String message;

 

        public String getCode() {

            return code;

        }

 

        public void setCode(String code) {

            this.code = code;

        }

 

        public String getMessage() {

            return message;

        }

 

        public void setCode(String message) {

            this.message = message;

        }

    }

 

 

[ RetrofitService.java ]

 

    public interface RetrofitService {

        @GET("/api/getdata")

        Call<Result> getData(@Query("authKey") String authKey, @Query("id") String id);

 

        @FormUrlEncoded

        @POST("/api/getdata")

        Call<Result> postData(@FieldMap HashMap<String, Object> param);

    }

 

 

[ API 호출 시, 반환되는 JSON ]

 

    {

        "code" : "SUCCESS",

        "message" : "정상적으로 조회되었습니다."

    }

 

 

[ MainActivity.java ]

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        ...

 

    Retrofit retrofit = new Retrofit.Builder()

              .baseUrl("http://localhost:8080")

              .addConverterFactory(GsonConverterFactory.create())

              .build();

 

    Result result = retrofit.create(Result.class);

 

    // GET

    result.getData("12345", "1").enqueue(new Callback<Result>() {

        @Override

        public void onResponse(@NonNull Call<Result> call, @NonNull Response<Result> response) {

            if(response.isSuccessful()) {  // 조회성공

                Result data = response.body();

                Log.d("code ", data.getCode();

                Log.d("message ", data.getMessage();

            }

        }

 

        @Override

        public void onFailure(Call<Result> call, Throwable t) {

            t.printStackTrace();

        }

    });

 

    // POST

    HashMap<String, Object> param = new HashMap<String, Object>();

    param.put("authKey", "12345");

    param.put("id", "1");

 

    result.postData(param).enqueue(new Callback<Result>() {

        @Override

        public void onResponse(@NonNull Call<Result> call, @NonNull Response<Result> response) {

            if(response.isSuccessful()) {  // 조회성공

                Result data = response.body();

                Log.d("code ", data.getCode();

                Log.d("message ", data.getMessage();

            }

        }

 

        @Override

        public void onFailure(Call<Result> call, Throwable t) {

            t.printStackTrace();

        }

    });

 

        ...

 

    }