안드로이드 REST API 연동 - andeuloideu REST API yeondong

1. Retrofit tutorial

Retrofit Tutorials
위 링크를 참고해서 만들었습니다.

2. 준비물

  • Android Studio
  • REST API
  • Retrofit

저는 여기서 REST APISpring Boot를 통해서 만들었습니다.

3. REST API에서 보낼 데이터


MySQL에 다음과 같은 데이터가 board table에 저장되어 있습니다.
이 데이터는 REST API에서 다음과 같은 코드를 통해 json 타입으로 서버에서 보내집니다.

@RestController @RequestMapping("/api") public class BoardApiController{ @Autowired private BoardRepository repository; @GetMApping("/boards") List<Board> all(){ return repository.findAll(); }

Spring Boot에서 바로 실행 했을 경우 주소창에 localhost:8080/api/boards를 입력하게 되면 다음과 같은 json타입으로 데이터가 나온 것을 볼 수 있습니다.

❗❗❗URL은 밑에 또 쓰이게 되니 집중해서 보기❗❗❗


다음 json data를 구성하는 id, title, content안드로이드 버츄얼 디바이스(AVD)에 출력해보겠습니다.

4. Android Studio Setting

각 파일마다 다음과 같은 코드를 입력해줍니다.

AndroidManifest.xml

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

build.gradle

dependencies{ implementation 'com.squareup.retrofit2:retrofit:2.4.0' implementation 'com.squareup.retrofit2:converter-gson:2.4.0' }

build.gradle 파일에 다음 코드를 작성했으면 상단에 sync now를 눌러주고 기다립니다.

5. Android code

Post.java

import com.google.gson.annotations.SerializedName; public class Post { private long id; private String title; private String content; public long getId() { return id; } public String getTitle() { return title; } public String getContent() { return content; } }

MainActivity.java

import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import java.util.List; 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("{서버를 돌릴 ip주소}:8080") .addConverterFactory(GsonConverterFactory.create()) .build(); JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class); Call<List<Post>> call = jsonPlaceHolderApi.getPosts(); call.enqueue(new Callback<List<Post>>() { @Override public void onResponse(Call<List<Post>> call, Response<List<Post>> response) { if (!response.isSuccessful()) { textViewResult.setText("Code: " + response.code()); return; } List<Post> posts = response.body(); for (Post post : posts) { String content = ""; content += "ID: " + post.getId() + "\n"; content += "Title: " + post.getTitle() + "\n"; content += "Content: " + post.getContent() + "\n\n"; textViewResult.append(content); } } @Override public void onFailure(Call<List<Post>> call, Throwable t) { textViewResult.setText(t.getMessage()); } }); } }

activity_main.xml

<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="//schemas.android.com/apk/res/android" xmlns:app="//schemas.android.com/apk/res-auto" xmlns:tools="//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="@color/purple_500" /> </androidx.core.widget.NestedScrollView> </androidx.constraintlayout.widget.ConstraintLayout>

RestApi.java

import java.util.List; import retrofit2.Call; import retrofit2.http.GET; public interface RestApi { @GET("api/boards") Call<List<Post>> getPosts(); }

자 여기서는 아까 Spring Boot를 실행해서 브라우저에 검색했던 localhost:8080/api/boardsapi/boards@Get 어노테이션 안에 넣어주게 되면 해당 URL로 매핑됩니다.

5. 출력화면

정상적으로 AVD에 Spring Boot에서 보낸 json 데이터가 출력된 것을 볼 수 있습니다.

6. 추가사항


다음과 같이 출력될 경우 네트워크 보안 정책상 권한을 받아야 하므로 AndroidManifest.xml에 다음과 같은 코드를 첨부해야 출력화면과 같이 정상적으로 데이터가 나오게 됩니다.

AndroidManifest.xml

<application> android:usesCleartextTraffic="true" </application>

IP주소 보는 법(Windows 10)

window키 + R → cmd 실행 → ipconfig 입력→ IPv4주소 확인

Toplist

최신 우편물

태그