출처: https://www.edwith.org/boostcourse-android/lecture/20488/



1. 구현 결과 화면

  



2. activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.tistory.qlyh8.practice.MainActivity">
 
    <LinearLayout
        android:id="@+id/layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:id="@+id/button"
            android:layout_width="120dp"
            android:layout_height="match_parent"
            android:text="요청하기"/>
        <EditText
            android:id="@+id/edit_text"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="https://m.naver.com"/>
    </LinearLayout>
 
    <ScrollView
        android:id="@+id/scroll_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/holo_blue_light"
        android:padding="10dp">
        <TextView
            android:id="@+id/text_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18sp"/>
    </ScrollView>
 
</LinearLayout>
 
cs



3. AndroidManifest.xml

인터넷 접근 권한을 부여한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tistory.qlyh8.practice">
 
    <uses-permission android:name="android.permission.INTERNET"/>
 
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name="com.tistory.qlyh8.practice.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>
cs



4. MainActivity.java

HTTP 클라이언트를 만드는 방법 중 하나는 HttpURLConnection 객체를 사용하는 것이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package com.tistory.qlyh8.practice;
 
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class MainActivity extends AppCompatActivity {
 
    EditText editText;
    TextView textView;
    String urlStr, responseStr;
    Handler handler = new Handler();
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        editText = findViewById(R.id.edit_text);
        textView = findViewById(R.id.text_view);
 
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RequestThread thread = new RequestThread();
                thread.start();
            }
        });
    }
 
    public class RequestThread extends Thread {
        @Override
        public void run() {
            urlStr = editText.getText().toString();
 
            try {
                URL url = new URL(urlStr);  // 받은 URL 로 URL 객체 생성
                HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // HttpURLConnection 객체 생성
 
                if(connection != null){
                    connection.setConnectTimeout(10000); // 10초 동안 기다린 후 응답이 없으면 종료
                    connection.setRequestMethod("GET"); // GET 방식으로 요청
                    connection.setDoInput(true);    // 서버로부터 받는 것을 가능하게 함
                    connection.setDoOutput(true);   // 서버로 보내는 것을 가능하게 함
 
                    int connectCode = connection.getResponseCode(); // 웹  서버에 연결하고 응답을 받음
                    //if(connectCode == HttpURLConnection.HTTP_OK) {...}
 
                    // 응답을 받을 BufferedReader 객체 생성
                    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
 
                    while (true){
                        responseStr = reader.readLine(); // 한 줄씩 문자열 읽기
 
                        if(responseStr == null)
                            break;
 
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                textView.append(responseStr  + "\n");  // 응답을 화면에 띄움
                            }
                        });
                    }
 
                    reader.close();
                    connection.disconnect();
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
cs


HttpURLConnection 클래스를 쓰면 스레드와 핸들러를 직접 작성해 코드 양이 많아지고, 신경쓸 것이 많다. 

이를 대신에 OkHttp, volley 라이브러리를 사용하여 보다 간단하게 웹에 요청하고 응답 받을 수 있다.

 


'Android' 카테고리의 다른 글

Volley 사용하기 - (2) JSON 요청하기  (1) 2018.07.31
Volley 사용하기 - (1)  (0) 2018.07.31
HTTP - 1. HTTP란  (0) 2018.07.30
소켓 (Socket) - 3. 소켓 사용하기 (2)  (0) 2018.07.28
소켓 (Socket) - 2. 소켓 사용하기 (1)  (0) 2018.07.25

+ Recent posts