프로그래밍/안드로이드

Http Post 방식으로 웹서버와 자료를 주고받는 예제

가카리 2013. 11. 18. 23:03
반응형

다음 프로그램은 http://korea-com.org/foxmann/lesson01.php 와 자료를 주고받는 예제이다.

[주의 사항]
1. http://korea-com.org/foxmann/lesson01.php 는 실습을 위해 임시로 만든 페이지이므로 언제든지 내 맘대로 삭제해 버릴 수 있다.
2. 위의 사이트를 해킹하는 행위는 형사 처벌을 받게 되므로 주의해야 한다.
3. 해킹 시도시 접속자의 ip를 추적해서 사용자의 컴퓨터를 포맷해 버리는 악랄한(?) 프로텍트를 사용하고 있으므로 특히 주의한다.

실행 결과 : 페이지1로 전송하고 페이지2로 결과 받음 








 

 

        

main.xml 

<?xml version="1.0" encoding="utf-8"?> 
<TabHost 
     xmlns:android="http://schemas.android.com/apk/res/android" 
      android:id="@android:id/tabhost"  
      android:layout_width="fill_parent"  
      android:layout_height="fill_parent"> 

      <LinearLayout  
            android:layout_width="fill_parent"  
            android:layout_height="fill_parent"  
            android:orientation="vertical">  

           <TabWidget  
                 android:id="@android:id/tabs"  
                 android:layout_width="fill_parent"  
                 android:layout_height="wrap_content"/> 

           <TextView 
                 android:layout_width="wrap_content"  
                 android:layout_height="wrap_content"/> 
           <FrameLayout  
                 android:id="@android:id/tabcontent"  
                 android:layout_width="fill_parent"  
                 android:layout_height="fill_parent"> 

            <TableLayout  
                  android:id="@+id/page01"  
                  android:layout_width="fill_parent"  
                  android:layout_height="wrap_content"  
                  android:stretchColumns="1"> 

             <TableRow> 
                   <TextView  
                         android:layout_width="wrap_content"  
                         android:layout_height="wrap_content" 
                         android:text="ID :"/> 
                   <EditText  
                          android:id="@+id/edit_Id"  
                          android:layout_width="fill_parent"  
                          android:layout_height="wrap_content"/> 
             </TableRow> 
             <TableRow> 
                   <TextView  
                         android:layout_width="wrap_content"  
                         android:layout_height="wrap_content"  
                         android:text="PWord : "/> 
                    <EditText  
                          android:id="@+id/edit_pword"  
                          android:layout_width="fill_parent"  
                          android:layout_height="wrap_content"  
                          android:password="true"/> 
             </TableRow> 
             <TableRow> 
                   <TextView  
                         android:layout_width="wrap_content"  
                         android:layout_height="wrap_content"  
                         android:text="개념 : "/> 
                    <EditText  
                          android:id="@+id/edit_title"  
                          android:layout_width="fill_parent"  
                          android:layout_height="wrap_content"/> 
             </TableRow> 
             <TableRow> 
                   <TextView  
                         android:layout_width="wrap_content"  
                         android:layout_height="wrap_content"  
                         android:text="대책 : "/> 
                    <EditText  
                          android:id="@+id/edit_subject"  
                          android:layout_width="fill_parent"  
                          android:layout_height="wrap_content"  
                          android:lines="4"/> 
             </TableRow> 
             <View  
                   android:layout_height="2dip"  
                   android:background="#AAAAAA"/> 
             <TableRow> 
                   <Button  
                         android:text="   전    송    "  
                         android:id="@+id/button_submit"  
                         android:layout_column="1" 
                         android:layout_width="wrap_content"  
                         android:layout_height="wrap_content"/> 
             </TableRow> 
       </TableLayout> 

  <LinearLayout  
        android:id="@+id/page02"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"> 
        <TextView  
              android:id="@+id/text_result"  
              android:layout_width="fill_parent"  
              android:layout_height="wrap_content"/> 
       </LinearLayout> 
   </FrameLayout>   
</LinearLayout> 
</TabHost>   


Manifest.xml에 다음과 같은 퍼미션을 줘야 한다.

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


project 


package com.http_post; 

import java.io.*; 
import java.net.*; 

import android.app.*; 
import android.os.*; 
import android.util.*; 
import android.view.*; 
import android.widget.*; 

public class MainActivity extends TabActivity { 
    // 전역변수를 선언한다 
    TabHost mTabHost = null; 
    String myId, myPWord, myTitle, mySubject, myResult; 
  
 //제가 수정했습니다. 아래  if(android.os.Build.VERSION.SDK_INT > 9)  넣어야 작동합니다.

//이유는 허니콤이상에서는 쓰레드를 만들어서 http통신을 해야되는데 이 소스는 그렇지 않게 만들어서

//강제적으로 실행하게 한 것입니다

           protected void onCreate(Bundle savedInstanceState) {

                     super.onCreate(savedInstanceState);

                         setContentView(R.layout.activity_main);

                        

                        

                         if(android.os.Build.VERSION.SDK_INT > 9) {//이거 넣어봄그래야 작동하네요.

 

                              StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

 

                              StrictMode.setThreadPolicy(policy);

                       

 

                    

                   mTabHost = getTabHost();        // Tab 만들기

                   mTabHost.addTab(mTabHost.newTabSpec("tab_1").setIndicator("서버로 전송").setContent(R.id.page01));

                   mTabHost.addTab(mTabHost.newTabSpec("tab_2").setIndicator("서버에서 받음").setContent(R.id.page02));

                   findViewById(R.id.button_submit).setOnClickListener(buttonClick); 

                    

                         }//strict mode

           }

          


    
    //------------------------------ 
    //    button Click 
    //------------------------------ 
    Button.OnClickListener buttonClick = new Button.OnClickListener() { 
        public void onClick(View v) { 
           // 사용자가 입력한 내용을 전역변수에 저장한다 
           myId = ((EditText)(findViewById(R.id.edit_Id))).getText().toString();  
           myPWord = ((EditText)(findViewById(R.id.edit_pword))).getText().toString();  
           myTitle = ((EditText)(findViewById(R.id.edit_title))).getText().toString();  
           mySubject = ((EditText)(findViewById(R.id.edit_subject))).getText().toString();  
    
           HttpPostData();   // 서버와 자료 주고받기 
       } 
    };  
    
    //------------------------------ 
    //   Http Post로 주고 받기 
    //------------------------------ 
    public void HttpPostData() { 
         try { 
              //-------------------------- 
              //   URL 설정하고 접속하기 
              //-------------------------- 
              URL url = new URL("http://korea-com.org/foxmann/lesson01.php");       // URL 설정 
              HttpURLConnection http = (HttpURLConnection) url.openConnection();   // 접속 
              //-------------------------- 
              //   전송 모드 설정 - 기본적인 설정이다 
              //-------------------------- 
              http.setDefaultUseCaches(false);                                            
              http.setDoInput(true);                         // 서버에서 읽기 모드 지정 
              http.setDoOutput(true);                       // 서버로 쓰기 모드 지정  
              http.setRequestMethod("POST");         // 전송 방식은 POST 

              // 서버에게 웹에서 <Form>으로 값이 넘어온 것과 같은 방식으로 처리하라는 걸 알려준다 
              http.setRequestProperty("content-type", "application/x-www-form-urlencoded"); 
              //-------------------------- 
              //   서버로 값 전송 
              //-------------------------- 
              StringBuffer buffer = new StringBuffer(); 
              buffer.append("id").append("=").append(myId).append("&");                 // php 변수에 값 대입 
              buffer.append("pword").append("=").append(myPWord).append("&");   // php 변수 앞에 '$' 붙이지 않는다 
              buffer.append("title").append("=").append(myTitle).append("&");           // 변수 구분은 '&' 사용  
              buffer.append("subject").append("=").append(mySubject); 
             
              OutputStreamWriter outStream = new OutputStreamWriter(http.getOutputStream(), "EUC-KR"); 
              PrintWriter writer = new PrintWriter(outStream); 
              writer.write(buffer.toString()); 
              writer.flush(); 
              //-------------------------- 
              //   서버에서 전송받기 
              //-------------------------- 
              InputStreamReader tmp = new InputStreamReader(http.getInputStream(), "EUC-KR");  
              BufferedReader reader = new BufferedReader(tmp); 
              StringBuilder builder = new StringBuilder(); 
              String str; 
              while ((str = reader.readLine()) != null) {       // 서버에서 라인단위로 보내줄 것이므로 라인단위로 읽는다 
                   builder.append(str + "\n");                     // View에 표시하기 위해 라인 구분자 추가 
              } 
              myResult = builder.toString();                       // 전송결과를 전역 변수에 저장 
             ((TextView)(findViewById(R.id.text_result))).setText(myResult); 
             Toast.makeText(MainActivity.this, "전송 후 결과 받음", 0).show(); 
         } catch (MalformedURLException e) { 
                // 
         } catch (IOException e) { 
                //  
         } // try 
    } // HttpPostData 
} // Activity 



lesson01.php


<?

$id = $_REQUEST[id];
$pword = $_REQUEST[pword];
$title = $_REQUEST[title];
$subject = $_REQUEST[subject];

// 변수 내용 확인
if ($id == "") $id = "ID도 없냐?";
if ($pword == "") $pword = "칠칠맞게 비밀번호도 잊어먹고 다니네...";
if ($title == "") $title = "증말 개념없는 사람일세...";
if ($subject == "") $subject = "에구~~ 대책이 없네...";
// 변수 내용 출력
echo ("
  님께서 PHP로 전송한 내용입니다
  -----------------------------------------------------------------\r\n
  사용자 ID : $id \r\n
  비밀번호 : $pword \r\n
  개념 : $title \r\n
  대책 : $subject \r\n
  -----------------------------------------------------------------\r\n
  축하드립니다. lesson01.php 를 정삭적으로 호출하셨습니다!
");
?>           



이렇게 까지 자세히 가르쳐 줘도 이해하지 못한 사람은 부모님을 원망해야 한다(원래 머리 나쁜 사람은 나도 어쩔 도리가 없음... ㅋㅋ)

Http로 파일 다운받는 것은 다음 기회에...            To be continued...


반응형