IT/Android

Networking - 웹으로 요청하기

바바옄 2015. 6. 24. 13:17
반응형

 

- 다른 스레드에서 메인스레드의 widget으로 접근할 수 없음 -> handler.post를 사용

 

 

MainActivity.java

 

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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package com.ktds.myrequestweb;
 
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
 
 
public class MainActivity extends ActionBarActivity {
 
    private EditText input01;
    private Button requestBtn;
    private TextView textMsg;
    private Handler handler;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // url 주소
        input01 = (EditText) findViewById(R.id.input01);
        requestBtn = (Button) findViewById(R.id.requestBtn);
        textMsg = (TextView) findViewById(R.id.textMsg);
 
        handler = new Handler();
 
        requestBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String urlStr = input01.getText().toString();
 
                // http 요청은 thread를 사용해야 한다.
                ConnectionThread thread = new ConnectionThread(urlStr);
                thread.start();
            }
        });
    }
 
    private class ConnectionThread extends Thread {
 
        private String urlStr;
 
        public ConnectionThread(String urlStr) {
            this.urlStr = urlStr;
        }
 
        @Override
        public void run() {
            final String output = request();
 
            // main thread에 있는 widget으로 접근 하려면 handler를 사용해야 한다.
            handler.post(new Runnable() {
                @Override
                public void run() {
                    textMsg.setText(output);
                }
            });
 
            // handler를 사용하지 않을 경우, 다른 스레드에서 메인스레드의 widget으로 접근할 수 없음.
            //textMsg.setText(output);
        }
 
 
        // http 요청을 하는 로직
        private String request() {
 
            StringBuffer output = new StringBuffer();
 
            try {
                URL url = new URL(urlStr);
 
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 
                if (conn != null) {
                    conn.setConnectTimeout(10000);
                    conn.setRequestMethod("GET");
                    conn.setDoInput(true);
                    conn.setDoOutput(true);
                }
 
                int resCode = conn.getResponseCode();
 
                if (resCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
 
                    String line = null;
 
                    while (true) {
                        line = reader.readLine();
                        if (line == null) {
                            break;
                        }
                        output.append(line + "\n");
                    }
                    reader.close();
                    conn.disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("HTTPRequest""Exception in processing response.", e);
            }
            return output.toString();
 
        }
    }
 
}
 
cs

 

 

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
<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=".MainActivity">
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:id="@+id/input01"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:hint="사이트 주소 입력"
            android:textSize="18dp"
            android:layout_weight="3"/>
 
        <Button
            android:id="@+id/requestBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="HTTP 요청"
            android:textSize="20dp"
            android:textStyle="bold"
            android:layout_weight="1"/>
 
        <ScrollView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
 
            <TextView
                android:id="@+id/textMsg"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#FF99CCEE"
                android:textColor="#FF0000FF"
                android:textSize="12dp"/>
 
        </ScrollView>
    </LinearLayout>
 
 
</LinearLayout>
 
cs

 

 

AndroidManifext.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
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ktds.myrequestweb" >
 
    <uses-permission android:name="android.permission.INTERNET"/>
 
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>
 
cs

 

 

           

 

 

 

 

반응형

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

View Pager  (0) 2015.06.25
Networking - API 요청하기  (0) 2015.06.24
Thead & Runnable  (0) 2015.06.24
1. Database를 이용한 전화번호부 실습  (0) 2015.06.23
Database  (0) 2015.06.23