[android] 안드로이드 데이터 연결

안드로이드 앱에서 HTTP 요청을 보내는 방법 중 하나는 HttpURLConnection 클래스를 사용하는 것입니다. 다음은 간단한 예시 코드입니다.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private static final String API_URL = "https://example.com/api/data";

    private void fetchDataFromServer() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(API_URL);
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                    urlConnection.setRequestMethod("GET");

                    int responseCode = urlConnection.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                        String inputLine;
                        StringBuffer response = new StringBuffer();
                        while ((inputLine = in.readLine()) != null) {
                            response.append(inputLine);
                        }
                        in.close();
                        // Handle the response data here
                        String responseData = response.toString();
                    } else {
                        // Handle the error
                    }
                    urlConnection.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

위 코드에서 fetchDataFromServer 메소드는 서버에서 데이터를 가져와 처리하는 역할을 합니다. HttpURLConnection을 사용하여 서버로 HTTP GET 요청을 보내고, 응답 데이터를 처리합니다.

안드로이드에서 HTTP 통신은 보안적인 이슈나 네트워크 연결 상태를 고려해야 하는 등 몇 가지 주의할 점이 있습니다. 따라서 안드로이드의 이러한 특성을 고려하여 데이터 연결을 구현하는 것이 중요합니다.

안드로이드 앱에서 데이터 연결을 다루는 것에 대해 더 많은 정보를 원하시면 안드로이드 공식 문서 및 안드로이드 개발자 커뮤니티의 참고 자료를 참조하시기 바랍니다.