[android] 안드로이드에서 HTTP 통신

안드로이드 앱에서 서버와의 HTTP 통신은 중요하고 일반적인 작업입니다. 안드로이드에서 HTTP 통신을 수행하려면 다음과 같은 방법을 사용할 수 있습니다.

  1. AsyncTask를 사용하여 백그라운드 스레드에서 HTTP 요청을 수행합니다.
  2. Volley나 Retrofit과 같은 HTTP 클라이언트 라이브러리를 사용하여 통신을 처리합니다.

AsyncTask를 사용한 HTTP 통신

public class HttpTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        try {
            URL url = new URL(urls[0]);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            try {
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                // InputStream을 가공하여 결과를 반환합니다.
                // ...
            } finally {
                urlConnection.disconnect();
            }
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    protected void onPostExecute(String result) {
        // 통신 결과를 처리합니다.
    }
}

Volley를 사용한 HTTP 통신

Volley는 안드로이드 앱에서 네트워크 작업을 수행하는 데 사용되는 라이브러리입니다.

// 요청 생성
String url = "https://api.example.com/data";
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
    new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            // 응답 처리
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            // 에러 처리
        }
    });

// 요청을 큐에 추가
queue.add(stringRequest);

Retrofit을 사용한 HTTP 통신

Retrofit은 안드로이드에서 HTTP API를 손쉽게 사용할 수 있도록 도와주는 라이브러리입니다.

public interface ApiService {
    @GET("data")
    Call<Data> getData();
}

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

ApiService service = retrofit.create(ApiService.class);
Call<Data> call = service.getData();
call.enqueue(new Callback<Data>() {
    @Override
    public void onResponse(Call<Data> call, Response<Data> response) {
        // 응답 처리
    }

    @Override
    public void onFailure(Call<Data> call, Throwable t) {
        // 에러 처리
    }
});

안드로이드 앱에서 HTTP 통신을 수행하는 여러 방법이 있지만, AsyncTask, Volley, Retrofit을 사용하는 것이 일반적입니다. 각 방법에는 장단점이 있으니 프로젝트 요구사항에 맞게 적절한 방법을 선택하는 것이 중요합니다.

참고문헌: