300x250
반응형
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();
}
});
...
}
출처 : https://roadrunner.tistory.com/648
300x250
반응형
'Back-End > 그 외' 카테고리의 다른 글
[Android] Retrofit2 @Body @Field 차이 (0) | 2023.02.09 |
---|---|
[Android] 사설 SSL 인증서를 이용한 https 통신 (0) | 2023.02.09 |
[Android] Android에서 SpringBoot JPA 서버와 연동하기 (0) | 2023.02.09 |
[Android] Android 와 Spring 연동 (0) | 2023.02.09 |
[Android] Retrofit POST 방식 간단 예제 (0) | 2023.02.09 |