OkHttp3 설정 및 기본 사용법
Android 프로젝트에 OkHttp3를 사용하려면 먼저 빌드 파일에 의존성을 추가해야 합니다.
dependencies {
implementation 'com.squareup.okhttp3:okhttp:3.4.2'
}
또한 인터넷 접근 권한을 앱의 AndroidManifest.xml에 선언해야 합니다.
<uses-permission android:name="android.permission.INTERNET" />
기본 GET 요청 예제
다음은 간단한 GET 요청을 수행하는 코드입니다. 비동기 방식으로 실행되며, 응답 결과는 백그라운드 스레드에서 처리됩니다.
public void performGetRequest(View view) {
OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(5000, TimeUnit.MILLISECONDS)
.build();
Request request = new Request.Builder()
.url("https://www.baidu.com")
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("NETWORK_ERROR", "요청 실패: " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
Log.d("RESPONSE", "응답 데이터: " + result);
// UI 업데이트는 메인 스레드에서 수행
runOnUiThread(() -> {
// 예: TextView에 결과 표시
});
}
});
}
POST 요청 (폼 데이터 전송)
서버에 폼 데이터를 전송할 때는 FormBody를 사용합니다.
public void performPostRequest(View view) {
OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(5000, TimeUnit.MILLISECONDS)
.build();
RequestBody body = new FormBody.Builder()
.add("showapi_appid", "27306")
.add("showapi_sign", "150e9206e7f542bab4affe49d73cb920")
.build();
Request request = new Request.Builder()
.url("http://route.showapi.com/578-6")
.post(body)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("POST_ERROR", "전송 실패: " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("POST_RESPONSE", "서버 응답: " + response.body().string());
}
});
}
파일 업로드 (멀티파트 요청)
이미지나 파일을 서버에 업로드할 경우, MultipartBody를 사용하여 형식을 지정합니다.
public void uploadFile(View view) {
OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(5000, TimeUnit.MILLISECONDS)
.build();
File file = new File("/path/to/your/image.jpg");
RequestBody fileBody = RequestBody.create(
MediaType.parse("application/octet-stream"), file);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("upload_field", "profile_image.jpg", fileBody)
.build();
Request request = new Request.Builder()
.url("http://192.168.18.250/upload")
.post(requestBody)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("UPLOAD_ERROR", "업로드 실패: " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("UPLOAD_RESULT", "업로드 성공: " + response.body().string());
}
});
}
모든 네트워크 작업은 비동기로 처리되어야 하며, 결과를 사용자 인터페이스에 반영할 때는 runOnUiThread() 또는 Handler를 사용해 메인 스레드에서 처리해야 합니다.