λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
πŸ’š 개발/μ•ˆλ“œλ‘œμ΄λ“œ

[μ•ˆλ“œλ‘œμ΄λ“œ] AsyncTask 와 HttpURLConnection ...(1) Android Sample Code

by devshin.kr 2021. 8. 26.
728x90
λ°˜μ‘ν˜•

 

AsyncTask λž€ 비동기 μž‘μ—…μ„ ν•  수 μžˆλ„λ‘ μ œκ³΅ν•˜λŠ” ν΄λž˜μŠ€μ΄λ‹€.

비동기λ₯Ό μ‚¬μš©ν•˜λŠ” μ΄μœ λŠ”,

λ™κΈ°μ‹μœΌλ‘œ μž‘μ—…μ„ ν•˜κ²Œ 되면 main thread μ—μ„œ A thread 둜 κ°€μ„œ μž‘μ—…μ„ ν•˜λ‹€κ°€.. A thread κ°€ λλ‚˜μ•Όλ§Œ λ‹€μ‹œ main thread 둜 λŒμ•„ 올 수 μžˆλ‹€. λ§Œμ•½ A thread κ°€ μž‘μ—…μ„ 끝내지 λͺ» ν•˜λ©΄,,, main thread λŠ” λ‹€μŒ μž‘μ—…μ„ ν•  수 μ—†λŠ” 것이닀.

λΉ„λ™κΈ°μ‹μœΌλ‘œ μž‘μ—…μ„ ν•˜κ²Œ 되면 main thread λŠ” main thread λŒ€λ‘œ.. A thread λŠ” A thread λŒ€λ‘œ... μž‘μ—…μ„ 진행할 수 있게 λœλ‹€.

 

HttpURLConnection 을 μ΄μš©ν•΄ jsp μ„œλ²„λ‘œ 데이터λ₯Ό 보내고, jsp μ„œλ²„λ‘œλΆ€ν„° 데이터λ₯Ό λ°›λŠ” κ°„λ‹¨ν•œ μƒ˜ν”Œμ„ λ§Œλ“€μ–΄ 보자.

λ°μ΄ν„°λŠ” JSONObject λ₯Ό 보내고 λ°›λŠ” 걸둜 예λ₯Ό λ“€μ–΄ 보겠닀.

 

 

- AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.devshin93.asynctasktest">

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>   <!-- μΆ”κ°€ -->
    <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/Theme.AsyncTaskTest"
        android:usesCleartextTraffic="true">   <!-- μΆ”κ°€ -->
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 

 

- res > layout > activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="vertical"
        android:background="#4F599F">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:gravity="center"
            android:text="AsyncTask 둜 HttpURLConnection μ‚¬μš©ν•˜κΈ°"
            android:textSize="18dp"
            android:textColor="@color/white"
            android:textStyle="bold"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="10dp"
        android:orientation="vertical"
        android:background="@color/white">
    </LinearLayout>


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

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:orientation="vertical"
                android:background="#4F599F">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:layout_marginBottom="10dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:gravity="center"
                    android:textColor="@color/white"
                    android:textSize="15dp"
                    android:text="λ³΄λ‚΄λŠ” κ°’" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="5dp"
                android:orientation="vertical"
                android:background="@color/white">
            </LinearLayout>

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

                <TextView
                    android:text="input 1 : "
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"/>

               <EditText
                   android:id="@+id/sendText1"
                   android:layout_width="match_parent"
                   android:layout_height="wrap_content"/>

            </LinearLayout>

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

                <TextView
                    android:text="input 2 : "
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"/>

                <EditText
                    android:id="@+id/sendText2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"/>

            </LinearLayout>


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

                <Button
                    android:id="@+id/async_btn"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:text="μ„œλ²„λ‘œλΆ€ν„° κ²°κ³Ό λ°›μ•„ 였기" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="40dp"
                    android:orientation="vertical"
                    android:background="#4F599F">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="10dp"
                        android:layout_marginBottom="10dp"
                        android:layout_marginLeft="10dp"
                        android:layout_marginRight="10dp"
                        android:gravity="center"
                        android:textColor="@color/white"
                        android:textSize="15dp"
                        android:text="받은 κ°’" />
                </LinearLayout>

                <TextView
                    android:id="@+id/getText"
                    android:layout_width="match_parent"
                    android:layout_height="100dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginTop="10dp"
                    android:layout_marginBottom="10dp"
                    android:background="@color/grey"/>

            </LinearLayout>
        </LinearLayout>

</LinearLayout>

 

 

- res > values > colors.xml 에 grey 색상을 ν•˜λ‚˜ μΆ”κ°€ν•΄ 쀬닀..

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#FF6200EE</color>
    <color name="purple_700">#FF3700B3</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>

    <color name="grey">#C0C0C0</color>
</resources>

 

 

- java > νŒ¨ν‚€μ§€λͺ… > MainActivity.java

package com.devshin93.asynctasktest;

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity  {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn = findViewById(R.id.async_btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // AsyncTask 객체 생성
                HttpUrlConnectionTest test = new HttpUrlConnectionTest();
                // μ‹œμž‘
                test.execute();
            }
        });
    }


    // AsyncTask<Params, Progress, Result>
    // Params : doInBackground 의 νŒŒλΌλ―Έν„° νƒ€μž…
    // Progress : onProgressUpdate 의 νŒŒλΌλ―Έν„° νƒ€μž…
    // Result : doInBackground 의 리턴 κ°’. -> onPostExecute 의 νŒŒλΌλ―Έν„° νƒ€μž….
    public class HttpUrlConnectionTest extends AsyncTask<String, Void, String> {

        EditText ed1 = findViewById(R.id.sendText1);
        EditText ed2 = findViewById(R.id.sendText2);

        String sInput1 = ed1.getText().toString();
        String sInput2 = ed2.getText().toString();

        @Override
        protected void onPreExecute() {
            // doInBackground() 이전에 μˆ˜ν–‰λ  μž‘μ—…
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... strings) {
            try {
                String url = "http://10.10.28.97:8090/AndroidAsyncTaskTest/test.jsp";
                URL obj = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

                conn.setReadTimeout(10000); // read μ‹œ νƒ€μž„μ•„μ›ƒ μ‹œκ°„
                conn.setConnectTimeout(15000);  // μ„œλ²„ 접속 μ‹œ μ—°κ²° νƒ€μž„μ•„μ›ƒ μ‹œκ°„
                conn.setRequestMethod("POST");  // POST λ°©μ‹μœΌλ‘œ μš”μ²­
                conn.setDoInput(true);  // InputStream 으둜 μ„œλ²„λ‘œλΆ€ν„° 응닡을 λ°›κ² λ‹€λŠ” μ˜΅μ…˜
                conn.setDoOutput(true); // OutputStream 으둜 POST 데이터λ₯Ό λ„˜κ²¨ μ£Όκ² λ‹€λŠ” μ˜΅μ…˜
                conn.setRequestProperty("Content-Type", "application/json");    // application/json ν˜•μ‹μœΌλ‘œ 전솑. (Request body μ „λ‹¬μ‹œ application/json 으둜 μ„œλ²„μ— 전달)
                conn.setRequestProperty("Cache-Control", "no-cache");

                // JSONObject 둜 데이터λ₯Ό λ¬Άμ—ˆλ‹€.
                JSONObject jsonObj = new JSONObject();
                jsonObj.put("input1", sInput1);
                jsonObj.put("input2", sInput2);

                // JSONObject 둜 묢은 데이터λ₯Ό toString().getBytes() ν•΄ 전솑
                OutputStream os = conn.getOutputStream();
                os.write(jsonObj.toString().getBytes());
                os.close();

                // 톡신 ν›„ μ„œλ²„λ‘œλΆ€ν„° κ°€μ Έ 온 μ‘λ‹΅μ½”λ“œ. 200 -> 성곡
                int retCode = conn.getResponseCode();
                if (retCode == HttpURLConnection.HTTP_OK) {

                    InputStream is = conn.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String line;
                    StringBuffer response = new StringBuffer();
                    while ((line = br.readLine()) != null) {
                        response.append(line);
                        response.append("");
                    }
                    br.close();

                    // μ„œλ²„μ—μ„œ 보낸 값이 JSONObject ν˜•μ‹μ΄λ‹ˆκΉŒ..
                    String sRet = response.toString();
                    JSONObject retJSONObj = new JSONObject(sRet);

                    if (retJSONObj.get("nRv").equals("0")) {
                        String retVal = (String)retJSONObj.get("sRet");
                        System.out.println("λ©”λ‘±"+retVal);
                        return retVal;
                    }

                    else {
                        System.out.println("ν‹€λ ·μˆ΄");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            // doInBackground() 이후에 μˆ˜ν–‰λ  μž‘μ—…
            // String s νŒŒλΌλ―Έν„°λŠ” doInBackground() 의 리턴값이닀.
            TextView tv = findViewById(R.id.getText);
            tv.setText(s);
        }
    }

}

 

 

 

μ„œλ²„ μƒ˜ν”Œ μ½”λ“œλŠ” λ‹€μŒ μž₯에 이어 μž‘μ„±ν•˜κ² λ‹€...

2021.09.14 - [개발/μ•ˆλ“œλ‘œμ΄λ“œ] - [μ•ˆλ“œλ‘œμ΄λ“œ] AsyncTask 와 HttpURLConnection ...(2) Web Sample Code (jsp)

 

[μ•ˆλ“œλ‘œμ΄λ“œ] AsyncTask 와 HttpURLConnection ...(2) Web Sample Code (jsp)

2021.08.26 - [개발/μ•ˆλ“œλ‘œμ΄λ“œ] - [μ•ˆλ“œλ‘œμ΄λ“œ] AsyncTask 와 HttpURLConnection ...(1) Android Sample Code [μ•ˆλ“œλ‘œμ΄λ“œ] AsyncTask 와 HttpURLConnection ...(1) Android Sample Code AsyncTask λž€ 비동기 μž‘..

devshin93.tistory.com

 

λ°˜μ‘ν˜•

λŒ“κΈ€