package net.apptools.network;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
EditText editText;
Button button;
TextView textView;
Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textView);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RequestThread thread = new RequestThread();
thread.start();
}
});
}
class RequestThread extends Thread {
public void run() {
//ÀÔ·Â »óÀÚ¿¡ ÀÔ·ÂµÈ URLÀ» °¡Á®¿È
String urlStr = editText.getText().toString();
try { //³×Æ®¿öÅ·Àº ¿¹¿Ü°¡ ¹ß»ýÇÒ ¼ö ÀÖ¾î¼ Excption ¿¡·¯°¡ ÀÚÁֹ߻ýÇÔ.
//http ¿äûÀ¸·Î ¾ÆÁÖ °£´ÜÈ÷ URL °´Ã¼¸¦ ¸¸µé¼ö ÀÖÀ½.
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setConnectTimeout(10000); //10ÃÊ µ¿¾È ÀÀ´ä ¾øÀ¸¸é ²÷À½.
int resCode = connection.getResponseCode(); //http ÀÀ´ä Äڵ带 ¹Þ±â
if(resCode == 200) { //¼¹ö Á¢¼ÓÀÌ Á¤»óÀÎ °æ¿ì ¼¹ö¿¡¼ 200 Äڵ带 º¸³»ÁÜ.
//connection¿¡ inputStreamÀ¸·Î ¹Þ°Ô µÇ´Âµ¥ ÇÑ ÁÙ¾¿ ¹ÞÀ»·Á¸é BufferReader
//·Î ¹ÞÀ¸¸é ¹Ù·Î º¯È¯ÀÌ ¾ÈµÇ¹Ç·Î InputStreamReader·Î Çѹø´õ °¨½ÎÁà¾ßÇÔ.
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), "UTF-8"));
//°á°ú¹°À» ´ãÀ»¼ö ÀÖ´Â StringBuilder
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while(true) {
//readLine() ÇÑÁÙ¾¿ ÀÐÀ» ¼ö ÀÖÀ½.
line = bufferedReader.readLine();
if(line == null) break;
stringBuilder.append(line + "\n");
}
bufferedReader.close();
connection.disconnect();
String result = stringBuilder.toString();
println(result); //ȸéÀÇ TextView¿¡ °á°ú Ãâ·Â (Çڵ鷯ÀÌ¿ë)
} else {
//resCode 200ÀÌ ¾Æ´Ñ °æ¿ì -> ¼¹ö ¿¡·¯
Toast.makeText(getApplicationContext(), "Á¢¼Ó¿À·ù : " + resCode, Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
//¾²·¹µå¿¡¼ UI¿¡ Á¢±Ù ÇÒ ¼ö ¾øÀ¸´Ï Çڵ鷯¸¦ ¸¸µé¾î ÁØ´Ù.
private void println(final String data) {
handler.post(new Runnable() {
@Override
public void run() {
textView.setText("");
textView.append(data + "\n");
}
});
}
}
[ÀÌ °Ô½Ã¹°Àº ÀÌ°æ¿ë´Ô¿¡ ÀÇÇØ 2016-12-22 20:52:32 ºÎ»ê20±â¿¡¼ º¹»ç µÊ]