YesYo.com MintState Forums
뒤로    YesYo.com MintState BBS > Tech > Android
검색
멤버이름    오토
비밀번호 
 

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

페이지 정보

작성자 MintState 댓글 0건 조회 11,604회 작성일 11-04-03 14:21

본문

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

다음 프로그램은 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;
 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		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); 
	}

	//------------------------------
	//    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
<?
// 변수 내용 확인
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://www.androidside.com/bbs/board.php?bo_table=421&wr_id=137
첨부 파일
파일 종류: png 전송화면.png (115.3K, 51 views)
파일 종류: png 받은화면.png (77.2K, 13 views)

댓글목록

등록된 댓글이 없습니다.

Total 18건 1 페이지
게시물 검색
모바일 버전으로 보기
CopyRight ©2004 - 2024, YesYo.com MintState. ™