HTTP 프로토콜은 비연결성(Stateless)인 특성을 가지고 있다.

페이지 정보를 요청할 때마다 소켓으로 웹 서버에 연결한 후에 요청을 전송하고, 응답을 받은 다음 소켓 연결을 끊는다.✂

 

 

자바에서 HTTP 클라이언트를 만드는 가장 간단한 방법 :

👉URL 객체를 만들고 openConnection 메서드를 호출하여 HttpURLConnection 객체를 만드는 것

URL url = new URL(urlString);
HttpURLConnection httpurlconnection = (HttpURLConnection) url.openConnection();

 

setRequestMethod() : 요청방식을 지정하는 메서드. GET이나 POST 문자열을 파라미터로 전달한다.

setConnectTimeout() : 연결 대기 시간(ms)

setDoInput() : 해당 객체의 입력이 가능하도록 설정 (ex. httpurlconnection.setDoInput(true))

 

 

🚩HTTP로 웹 서버에 접속하기

GET 방식을 사용하여 웹페이지 주소를 입력하면 해당 페이지의 내용을 가져오는 앱을 구현한다.

(참고로 결과가 제대로 나오지 않는데, 이번 예제가 원래 그런거다.)

 

1️⃣activity_main.xml

더보기
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editTextText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:background="@drawable/box"
        android:ems="10"
        android:hint="사이트 주소 입력"
        android:inputType="text"
        android:padding="10dp"
        android:textSize="24sp" />

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="요청하기" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/textView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="TextView"
                android:textSize="20sp" />
        </LinearLayout>
    </ScrollView>
</LinearLayout>

 

2️⃣MainActivity.java

 

🔹전체코드🔹

더보기
package com.example.chapter10_3;

public class MainActivity extends AppCompatActivity {

    EditText editText;
    TextView textView;
    Handler handler = new Handler();

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

        editText = findViewById(R.id.editTextText);
        textView = findViewById(R.id.textView);

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String urlString = editText.getText().toString();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        request(urlString); // request 메서드 작성
                    }
                }).start();
            }
        });
    }

    private void request(String urlString) {
        StringBuilder output = new StringBuilder();

        try{
            URL url = new URL(urlString);
            HttpURLConnection urlconnection = (HttpURLConnection) url.openConnection();
            // URL 객체를 만들고 openConnection 메서드를 호출하여 HttpURLConnection 객체를 만들기

            if(urlconnection!=null){
                urlconnection.setConnectTimeout(10000); // 연결대기 시간 10초로 설정
                urlconnection.setRequestMethod("GET"); // GET 방식으로 요청
                urlconnection.setDoInput(true); // 해당 객체의 입력이 가능하도록 설정

                int resCode = urlconnection.getResponseCode();
                // 정상 응답코드 : HTTP_OK
                BufferedReader reader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream()));
                // readLine 메서드를 사용하기 위해 urlconnection 스트림을 BufferedReader 객체로 만든다.

                String line = null;
                while(true){
                    line = reader.readLine(); // readLine : 스트림에서 한 줄씩 읽어들이는 메서드
                    if(line==null)
                        break;

                    output.append(line+"\n");
                }

                reader.close();
                urlconnection.disconnect();
            }

        }catch (Exception ex){
            println("예외 발생함 : "+ex.toString());
        }

        println("응답 -> "+output);

    }

    // 출력 메서드
    private void println(String data) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                textView.append(data + "\n");
            }
        });
    }
}

🔹onCreate - onClick🔹

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String urlString = editText.getText().toString();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        request(urlString); // request 메서드 작성
                    }
                }).start();
            }
        });

인터넷을 사용하기 때문에 onClick 안에 스레드를 만든다.

editText에 입력된 url 문자열을 request 메서드에 넣는다.

 

🔹request 메서드🔹

    private void request(String urlString) {
        StringBuilder output = new StringBuilder();

        try{
            URL url = new URL(urlString);
            HttpURLConnection urlconnection = (HttpURLConnection) url.openConnection();
            // URL 객체를 만들고 openConnection 메서드를 호출하여 HttpURLConnection 객체를 만들기

            if(urlconnection!=null){
                urlconnection.setConnectTimeout(10000); // 연결대기 시간 10초로 설정
                urlconnection.setRequestMethod("GET"); // GET 방식으로 요청
                urlconnection.setDoInput(true); // 해당 객체의 입력이 가능하도록 설정

                int resCode = urlconnection.getResponseCode();
                // 정상 응답코드 : HTTP_OK
                BufferedReader reader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream()));
                // readLine 메서드를 사용하기 위해 urlconnection 스트림을 BufferedReader 객체로 만든다.

                String line = null;
                while(true){
                    line = reader.readLine(); // readLine : 스트림에서 한 줄씩 읽어들이는 메서드
                    if(line==null)
                        break;

                    output.append(line+"\n");
                }

                reader.close();
                urlconnection.disconnect();
            }

        }catch (Exception ex){
            println("예외 발생함 : "+ex.toString());
        }

        println("응답 -> "+output);
    }

 

StringBuilder 객체를 사용해서 출력 문자열(output)을 생성한다. (String 객체로 만들 시, String 객체의 덧셈 연산이 많아질수록 성능이 좋지 않기 때문에 StringBuilder를 사용한다.)

 

while문으로 한줄씩 모두 output에 추가한 다음, 모두 추가한 뒤에

reader는 닫고 urlconnection도 연결을 끊는다.

 

🔹println 메서드🔹

    private void println(String data) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                textView.append(data + "\n");
            }
        });
    }

 핸들러를 사용하여 텍스트뷰에 문자열을 출력한다.

 

3️⃣AndroidManifest.xml

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:usesCleartextTraffic="true"

 

4️⃣실행 결과

 

책에 나와있는 링크를 입력했다. 그런데 책에서 나온 결과와는 다르게 '유효하지 않은 키값'이라는 메시지가 나타났다.

이 주소 안에 들어있는 key 값은 직접 사이트에 등록해서 발급받아야 한다고 한다. 저렇게 나올 수밖에 없다고 함.

 

응답 결과물의 포맷은 JSON이며 이후 이 문자열을 어떻게 처리하는 지에 대해 다룬다고 함.

 

링크 주소 복붙도 안되고(에뮬레이터라서..) 링크 주소 길어서 틀릴까봐 하나하나 열심히 입력했는데 저런 결과를 보니 허무하군..