[ 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();
}
});
...
}
'프로그램 > Android' 카테고리의 다른 글
[Android Studio] SDK location not found (1) | 2021.06.15 |
---|---|
[Android Studio] Plugin Error: Plugin "Android WiFi ADB" is incompatible (supported only in IntelliJ IDEA). (0) | 2021.04.06 |
java.net.SocketException: socket failed: EACCES (Permission denied) (0) | 2021.02.20 |
[Kotlin] Naver 지도 표시하기 - <FrameLayout> (0) | 2019.04.16 |
[Kotlin] Naver 지도 표시하기 - <fragment > (0) | 2019.04.13 |