반응형
0. Retrofit
안드로이에서 서버와 HTTP 통신을 도와주는 유명한 라이브러리 중 하나!
기존의 HttpUrlConnection은 이제 안쓰고 Okhttp에서 나온 라이브러리인 Retrofit을 많이 쓴다고 합니다.
Retrofit의 동작 흐름
인터페이스 > Retrofit > Service (알아서 Call 객체 반환)
개발자가 해야하는 일은 인터페이스 작성
1. build.gradle 세팅
implementation 'com.squareup.retrofit2:retrofit:2.6.0'
implementation 'com.squareup.retrofit2:converter-gson:2.6.0'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
GSON은
// 서버와 통신할 데이터 타입에 맞는 컨버터 지정 (Gson 라이브러리 파싱, 데이터를 Model에 담아줌)
2. Manifest.xml
// 통신
<uses-permission android:name="android.permission.INTERNET" />
// 서버가 HTTP일 때는 적어줘야 함 (Https는 X)
<application android:usesCleartextTraffic="true" />
Http인데 아래 코드를 기입하지 않아서 한참 헤맸음,,
3. Model.Java
public class Member {
private String id;
private String name;
private int age;
private String address;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Member{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}';
}
}
4. JsonApi.Java
interface 생성
public interface JsonApi {
@GET("member/all")
Call<List<Member>> getMember();
}
5. MainActivity.Java
ublic class MainActivity extends AppCompatActivity {
TextView textView;
Retrofit retrofit;
JsonApi jsonApi;
Call<List<Member>> call;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
retrofit = new Retrofit.Builder()
.baseUrl("http://10.0.2.2:8080/") //베이스 url등록
.addConverterFactory(GsonConverterFactory.create())
.build();
jsonApi = retrofit.create(JsonApi.class);
call = jsonApi.getMember();
call.enqueue(new Callback<List<Member>>() {
@Override
public void onResponse(Call<List<Member>> call, Response<List<Member>> response) {
if (response.isSuccessful()) {
//layout에서 textview id = txt_json
textView = (TextView) findViewById(R.id.txt_json);
textView.setText(response.body().toString());
}
}
@Override
public void onFailure(Call<List<Member>> call, Throwable t) {
Log.e("MainActivity!!!", "실패");
t.printStackTrace();
}
});
}
}
// enqueue 함수 호출 Callback 클래스의 객체를 매개변수로 지정, 네트워킹 시도
// 서버에서 정상 결과 받으면 자동으로 onResponse()함수 호출
// 결과 데이터가 전달 실패시, onFailure() 함수
+로컬 호스트에 접속하는 URL
에뮬레이터 : http://10.0.2.2:8080
디바이스 연결 : 실제 내부 Ipv4로 접속
반응형
'SPRING' 카테고리의 다른 글
[전자정부 표준프레임워크] 3.9.0 all-in-one with Oracle 11g (0) | 2021.08.10 |
---|---|
[JSP, JSTL] JSP가 무엇인가, JSTL 태그 사용법 (0) | 2021.08.05 |
[스프링 부트] int 값 받아오는 법 (0) | 2021.06.19 |
[스프링] c:choose로 상태에 따른 값 출력하는 법 (0) | 2021.06.11 |
c:forEach : var, items, varStatus 정리 (0) | 2021.06.11 |