2019. 2. 9. 12:50ㆍ[정리] 직무별 개념 정리/안드로이드
1.매니페스트에 인터넷 통신을위한 권한 허용
<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <uses-permission android:name="android.permission.INTERNET" /> </manifest> |
2. Gradle을 이용하여 Retrofit을 설치
dependencies { implementation 'com.google.code.gson:gson:2.7' implementation 'com.squareup.retrofit2:retrofit:2.1.0' implementation 'com.squareup.retrofit2:converter-gson:2.1.0' } |
3. DTO 작성
public class Member { private String id; private String name; public String getId(){ return id; } public String getName(){ return name; } } |
4. Service 작성
public interface RetrofitMemberService { @GET("/member/{id}") Call<Member> getMember(@Path("id") String id);
@GET("/members") Call<List<Member>> getMembers();
@FormUrlEncoded @POST("/member") Call<Member> postMember(@FieldMap HashMap<String, Object> param);
@FormUrlEncoded @POST("/member") Call<Member> postMemberByJson(@Body Member param); @PUT("/member") Call<Member> putMember(@Body Member param);
@DELETE("/member") Call<ResponseBody> deleteMember(); } |
5. Retrofit 사용
public class MainActivity extends AppCompatActivity { private Retrofit retrofit; private RetrofitMemberService retrofitMemberService;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); buildRetrofit(); createRetrofitService(); callRetrofitGetAPI(); callRetrofitPostAPI(); }
private void buildRetrofit(){ retrofit = new Retrofit.Builder() .baseUrl("http://baseUrl.com") .addConverterFactory(GsonConverterFactory.create()) .build(); }
private void createRetrofitService(){ retrofitMemberService = retrofit.create(RetrofitMemberService.class); }
private void callRetrofitGetAPI(){ RetrofitMemberService.getMember("kok202").enqueue(new Callback<Member>() { @Override public void onResponse(@NonNull Call<Member> call, @NonNull Response<Member> response) { if (!response.isSuccessful()) return; Member member = response.body(); String id = member.getId(); String name = member.getName(); }
@Override public void onFailure(@NonNull Call<Member> call, @NonNull Throwable t) {
} }); }
private void callRetrofitGetAPI(){ HashMap<String, Object> input = new HashMap<>(); input.put("id", "Bpone"); input.put("name", "Hong gil dong"); retrofitMemberService.postData(input).enqueue(new Callback<Member>() { @Override public void onResponse(@NonNull Call<Member> call, @NonNull Response<Member> response) { if (!response.isSuccessful()) return; Member member = response.body(); String id = member.getId(); String name = member.getName(); }
@Override public void onFailure(@NonNull Call<Member> call, @NonNull Throwable t) {
} }); } } |
더 자세한 내용 : https://kor45cw.tistory.com/5
'[정리] 직무별 개념 정리 > 안드로이드' 카테고리의 다른 글
[2019.02.11] Retrofit custom builder (0) | 2019.02.11 |
---|---|
[2019.01.30] AsyncTask, API 호출 (0) | 2019.01.30 |