Android Http Https


HTTP와 HTTPS는 웹 통신을 위해 사용되는 두 가지 프로토콜입니다. HTTP는 HyperText Transfer Protocol의 약자로, 인터넷을 통해 데이터를 전송하는 데 사용됩니다. HTTPS는 HTTP Secure의 약자로, HTTP에 SSL/TLS 암호화를 추가하여 데이터를 안전하게 전송합니다.

HTTP와 HTTPS의 차이점

  • 보안: HTTP는 데이터를 암호화하지 않고 전송하기 때문에 중간에서 데이터가 도청될 수 있습니다. 반면, HTTPS는 SSL/TLS를 사용하여 데이터를 암호화하여 전송하므로, 데이터의 기밀성과 무결성이 보장됩니다.
  • 속도: HTTPS는 추가적인 암호화/복호화 과정을 거치기 때문에 약간의 성능 오버헤드가 발생할 수 있습니다.
  • 인증서: HTTPS는 서버의 신원을 확인하기 위해 SSL/TLS 인증서를 사용합니다. 이를 통해 클라이언트는 자신이 통신하는 서버가 신뢰할 수 있는 서버임을 확인할 수 있습니다.
  • 포트: HTTP는 기본적으로 포트 80을 사용하며, HTTPS는 포트 443을 사용합니다.

HTTP와 HTTPS 예제

아래 예제에서는 Volley 라이브러리를 사용하여 HTTP와 HTTPS 요청을 보내는 방법을 설명합니다.

Volley 의존성 추가

build.gradle 파일에 Volley 라이브러리 종속성을 추가합니다.

dependencies {
    implementation 'com.android.volley:volley:1.2.1'
}

HTTP 요청 예제

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String url = "http://jsonplaceholder.typicode.com/todos/1"; // HTTP URL

        RequestQueue queue = Volley.newRequestQueue(this);

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
                Request.Method.GET,
                url,
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            String title = response.getString("title");
                            Log.d("HTTP", "Title: " + title);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }
                }
        );

        queue.add(jsonObjectRequest);
    }
}

HTTPS 요청 예제

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String url = "https://jsonplaceholder.typicode.com/todos/1"; // HTTPS URL

        RequestQueue queue = Volley.newRequestQueue(this);

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
                Request.Method.GET,
                url,
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            String title = response.getString("title");
                            Log.d("HTTPS", "Title: " + title);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }
                }
        );

        queue.add(jsonObjectRequest);
    }
}

추가적인 보안 설정 (HTTPS)

HTTPS 요청을 수행할 때, SSL 인증서를 신뢰하지 않는 경우 SSL 핸드셰이크 오류가 발생할 수 있습니다. 이러한 문제를 해결하려면, 신뢰할 수 있는 인증서를 사용하거나, 필요할 경우 특정 인증서를 수락하도록 설정할 수 있습니다.

자체 서명된 인증서 허용 (비추천)

개발 중 자체 서명된 인증서를 허용하기 위해, 아래와 같은 방식으로 SSL 설정을 할 수 있습니다. 하지만 이는 프로덕션 환경에서는 절대 사용해서는 안 됩니다.

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 신뢰할 수 없는 SSL 인증서 허용 설정
        handleSSLHandshake();

        String url = "https://self-signed.badssl.com/"; // HTTPS URL with self-signed certificate

        RequestQueue queue = Volley.newRequestQueue(this);

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
                Request.Method.GET,
                url,
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("HTTPS", "Response: " + response.toString());
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }
                }
        );

        queue.add(jsonObjectRequest);
    }

    /**
     * Handles SSL handshake to trust all certificates.
     */
    @SuppressLint("TrustAllX509TrustManager")
    private void handleSSLHandshake() {
        try {
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[]{};
                        }

                        @Override
                        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        }
                    }
            };

            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
        }
    }
}

이 설정은 개발 중에만 사용하고, 배포 버전에서는 신뢰할 수 있는 인증서를 사용하여 보안 문제를 해결해야 합니다.

요약

  • HTTP는 데이터가 암호화되지 않은 상태로 전송되며, 보안에 취약합니다.
  • HTTPS는 SSL/TLS를 사용하여 데이터를 암호화하고 안전하게 전송합니다.
  • Volley와 Retrofit과 같은 네트워크 라이브러리를 사용하면 HTTP와 HTTPS 요청을 쉽게 처리할 수 있습니다.
  • HTTPS를 사용할 때는 반드시 신뢰할 수 있는 인증서를 사용하여 보안성을 확보해야 합니다.

Leave a Reply

Your email address will not be published. Required fields are marked *