Design-loving front-end engineer
Ryong
Design-loving front-end engineer
전체 방문자
오늘
어제
    • Framework
    • React
      • Concept
      • Library
      • Hook
      • Component
      • Test
    • NodeJS
    • Android
      • Concept
      • Code
      • Sunflower
      • Etc
    • Flutter
      • Concept
      • Package
    • Web
    • Web
    • CSS
    • Language
    • JavaScript
    • TypeScript
    • Kotlin
    • Dart
    • Algorithm
    • Data Structure
    • Programmers
    • Management
    • Git
    • Editor
    • VSCode
    • Knowledge
    • Voice
Design-loving front-end engineer

Ryong

[Android] [Kotlin] 네트워크
Android/Concept

[Android] [Kotlin] 네트워크

2021. 9. 25. 21:13

HTTP

URL의 구조

 

HTTP의 구조

 

HTTP 요청 방식

 

HTTP 응답(상태) 코드

 

앱 만들기

build.gradle

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9'

 

AndroidManifest.xml

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

 

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
42
43
44
45
46
47
48
49
50
51
52
53
54
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <EditText
        android:id="@+id/editUrl"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:ems="10"
        android:hint="주소를 입력하세요"
        android:inputType="textPersonName"
        android:textSize="24sp"
        app:layout_constraintEnd_toStartOf="@+id/buttonRequest"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
    <Button
        android:id="@+id/buttonRequest"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="요청"
        android:textSize="24sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
    <TextView
        android:id="@+id/textContent"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="16dp"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editUrl" />
</androidx.constraintlayout.widget.ConstraintLayout>
cs

 

MainActivity.kt

class MainActivity : AppCompatActivity() {

    val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        binding.buttonRequest.setOnClickListener {
            CoroutineScope(Dispatchers.IO).launch {
                try {
                    var urlText = binding.editUrl.text.toString()
                    if (!urlText.startsWith("https")) {  // 보안 문제로 인해 https로 시작하지 않으면
                        urlText = "https://${urlText}"  // https://를 붙여준다.
                    }

                    val url = URL(urlText)
                    val urlConnection = url.openConnection() as HttpURLConnection /*                      
                      * openConnection() 메서드를 사용하여 서버와의 연결을 생성
                      * openConnection() 메서드에서 반환되는 값은 URLConnection이라는 추상 클래스이다.
                      * 추상 클래스를 사용하기 위해서는 실제 구현 클래스인 HttpURLConnection으로 변환하는 과정이 필요  */

                    urlConnection.requestMethod = "GET"  // 연결된 커넥션이 요청 방식 설정

                    if (urlConnection.responseCode == HttpURLConnection.HTTP_OK) {
                        /* 입력 스트림(데이터를 읽어오는 스트림)을 연결하고 버퍼에 담아서 데이터를 읽을 준비 */
                        val streamReader = InputStreamReader(urlConnection.inputStream)
                        val buffered = BufferedReader(streamReader)

                        /* 반복문을 돌면서 한 줄씩 읽은 데이터를 content 변수에 저장 */
                        val content = StringBuilder()
                        while (true) {
                            val line = buffered.readLine() ?: break
                            content.append(line)
                        }

                        /* 사용한 스트림과 커넥션을 모두 해제 */
                        buffered.close()
                        urlConnection.disconnect()

                        /* 텍스트뷰에 content 변수에 저장된 값을 입력, 코루틴의 Main 디스패처에서 실행 */
                        launch(Dispatchers.Main) {
                            binding.textContent.text = content.toString()
                        }
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }
}

저작자표시 (새창열림)

'Android > Concept' 카테고리의 다른 글

[Android] [Kotlin] 파일 입출력  (0) 2021.09.26
[Android] [Kotlin] Retrofit  (0) 2021.09.25
[Android] [Kotlin] 콘텐트 리졸버  (0) 2021.09.23
[Android] [Kotlin] 서비스  (0) 2021.09.22
[Android] [Kotlin] 코루틴  (0) 2021.09.21
    'Android/Concept' 카테고리의 다른 글
    • [Android] [Kotlin] 파일 입출력
    • [Android] [Kotlin] Retrofit
    • [Android] [Kotlin] 콘텐트 리졸버
    • [Android] [Kotlin] 서비스
    Design-loving front-end engineer
    Design-loving front-end engineer
    디자인에 관심이 많은 모바일 앱 엔지니어 Ryong입니다.

    티스토리툴바