Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Tags more
Archives
Today
Total
관리 메뉴

맨땅에 코딩

[안드로이드] 웹 서버에 데이터 요청 (Open API 활용) 본문

앱 개발/Java

[안드로이드] 웹 서버에 데이터 요청 (Open API 활용)

맨땅 2022. 3. 30. 10:09

목차

    반응형

     

    영화진흥위원회의 오픈 API를 활용했습니다.

     

     

    https://www.kobis.or.kr/kobisopenapi/homepg/apiservice/searchServiceInfo.do

     

    영화진흥위원회 오픈API

    제공서비스 영화관입장권통합전산망이 제공하는 오픈API서비스 모음입니다. 사용 가능한 서비스를 확인하고 서비스별 인터페이스 정보를 조회합니다.

    www.kobis.or.kr

     

    사이트에 들어가셔서 맨 아래의 응답 예시에서 JSON 부분을 사용했습니다. 전체 복사하신후 입력해주시면 됩니다 

     

     


     

     

    우선 오픈 API를 사용하기 위해 Manifest에 필요한 권한을 추가해줍니다

     

     

    [AndroidManifest.xml]

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

     

    userCleartextTraffic 속성도 꼭 true로 바꿔주셔야 합니다!!!!

    왜냐하면?

    android:usesCleartextTraffic는 모든 Http 사이트에 대한 접근을 허용합니다. 만약 몇몇 사이트에 대한 접근만 허용하려면 /res/xml/network_security_config.xml 파일을 생성하고 예외 항목들을 추가해야 합니다.

     

     

    [MainActivity.java]

    package org.techtown.samplehttp;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.os.Bundle;
    import android.os.Handler;
    import android.view.View;
    import android.widget.Button;
    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;
    
        Handler handler = new Handler();
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            editText = findViewById(R.id.editText);
            textView = findViewById(R.id.textView);
    
            Button button = findViewById(R.id.button);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final String urlStr = editText.getText().toString();
    
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            request(urlStr); //request메서드 안에서 인터넷을 사용할 것이므로 Thread 안에서 동작하도록 Thread 객체 생성
                        }
                    }).start();
                }
            });
        }
    
        public void request(String urlStr){ // 응답 결과물 모아 화면에 출력
            StringBuilder output = new StringBuilder();
            try {
                URL url = new URL(urlStr); // url 객체 만들어
    
                HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 파라미터로 전달된 url 문자열을 이용해 openconnection 메서드 호출 => HttURL 객체 반환
                if (conn != null) {
                    conn.setConnectTimeout(10000); // 연결 대기 시간 설정 (10초 동안 연결 대기)
                    conn.setRequestMethod("GET"); //GET 방식으로 요청하는 내용 setRequestMethod로 설정
                    conn.setDoInput(true); // 이 객체의 입력이 가능하도록 true
    
                    int resCode = conn.getResponseCode(); // 메서드 호출 => 이 시점에 내부적으로 웹 서버에 페이지를 요청하는 과정 수행
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); //응답으로 들어온 스트림 문자열로 변환하여 반환
                    String line = null;
                    while (true) { // 응답코드가 HTTP_OK 인 경우
                        line = reader.readLine();  //readLine = 스트림에서 한 줄씩 읽어 들이는 메서드
                        if (line == null) {
                            break;
                        }
                        output.append(line + "\n");
                    }
                    reader.close();
                    conn.disconnect();
                }
            } catch (Exception ex) {
                println("예외 발생함: " + ex.toString());
            }
            println("응답-> " + output.toString());
    
        }
        public void println(final String data) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    textView.append(data + "\n");
                }
            });
        }
    }

     

     

     

    [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:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity">
    
        <EditText
            android:id="@+id/editText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPersonName"
            android:hint="사이트 주소 입력" />
    
        <Button
            android:id="@+id/button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Button" />
    
        <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:textSize="20sp" />
            </LinearLayout>
        </ScrollView>
    </LinearLayout>

     

     

    실행화면입니다. 이렇게 뜨시면 맞게 하신겁니다

     

     

    궁금하신 점은 편하게 질문 주세요! 감사합니다

     

     

     

    반응형