안 드 로 이 드 http 프로 그래 밍 노트

템 플 릿 파일
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
	<TextView 
	    android:id="@+id/tv_user"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:text="   "
	    />
	<EditText 
	    android:id="@+id/et_user"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:hint="      "
	    />
	<TextView 
	    android:id="@+id/tv_pass"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:text="  "
	    />
	<EditText 
	    android:id="@+id/et_pass"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:hint="     "
	    />
	<Button 
	    android:id="@+id/button"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="get  "
	    android:onClick="getLogin"
	    />
	<Button 
	    android:id="@+id/button2"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="post  "
	    android:onClick="postLogin"
	    />
	<Button 
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="httpClientGet  "
	    android:onClick="clientGetLogin"
	    />
	<Button 
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="httpClientPost  "
	    android:onClick="clientPostLogin"
	    />
</LinearLayout>

MainActivity
package com.http.action;

import com.login.service.LoginService;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;

public class MainActivity extends Activity {
	protected static final int LOGIN_SUCCESS = 1;
	protected static final int LOGIN_ERROR = 2;
	private EditText et_user;
	private EditText et_pass;
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message message)
		{
			switch (message.what) {
				case LOGIN_SUCCESS:
					Toast.makeText(MainActivity.this, (String) message.obj, Toast.LENGTH_SHORT).show();
					break;
				case LOGIN_ERROR:
					Toast.makeText(MainActivity.this, "    ", Toast.LENGTH_SHORT).show();
					break;
			}
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		et_user = (EditText) findViewById(R.id.et_user);
		et_pass = (EditText) findViewById(R.id.et_pass);
	}
	
	/**
	 *   
	 * @param view
	 */
	public void getLogin(View view)
	{
		final String user = et_user.getText().toString().trim();
		final String pass = et_pass.getText().toString().trim();
		new Thread(){
			public void run()
			{
				String res = LoginService.byGetLogin(user, pass);
				if (res != null) {
					Message msg = new Message();
					msg.what = LOGIN_SUCCESS;
					msg.obj = res;
					handler.sendMessage(msg);
				} else {
					Message msg = new Message();
					msg.what = LOGIN_ERROR;
					handler.sendMessage(msg);
				}
			}
		}.start();
	}
	
	/**
	 * post     
	 * @param view
	 */
	public void postLogin(View view)
	{
		final String user = et_user.getText().toString().trim();
		final String pass = et_pass.getText().toString().trim();
		new Thread(){
			public void run()
			{
				String text = LoginService.byPostLogin(user, pass);
				if (text != null) {
					Message msg = new Message();
					msg.what = LOGIN_SUCCESS;
					msg.obj = text;
					handler.sendMessage(msg);
				} else {
					Message msg = new Message();
					msg.what = LOGIN_ERROR;
					handler.sendMessage(msg);
				}
			}
		}.start();
	}
	
	/**
	 * client get login
	 * @param view
	 */
	public void clientGetLogin(View view)
	{
		final String user = et_user.getText().toString().trim();
		final String pass = et_pass.getText().toString().trim();
		new Thread(){
			public void run()
			{
				String res = LoginService.httpClientGetLogin(user, pass);
				if (res != null) {
					Message msg = new Message();
					msg.what = LOGIN_SUCCESS;
					msg.obj = res;
					handler.sendMessage(msg);
				} else {
					Message msg = new Message();
					msg.what = LOGIN_ERROR;
					handler.sendMessage(msg);
				}
			}
		}.start();
	}
	
	/**
	 * client post login
	 * @param view
	 */
	public void clientPostLogin(View view)
	{
		final String user = et_user.getText().toString().trim();
		final String pass = et_pass.getText().toString().trim();
		new Thread(){
			public void run()
			{
				String res = LoginService.httpClientPostLogin(user, pass);
				if (res != null) {
					Message msg = new Message();
					msg.what = LOGIN_SUCCESS;
					msg.obj = res;
					handler.sendMessage(msg);
				} else {
					Message msg = new Message();
					msg.what = LOGIN_ERROR;
					handler.sendMessage(msg);
				}
			}
		}.start();
	}
}

LoginService
package com.login.service;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpConnection;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.stream.utils.Stream;

public class LoginService 
{
	/**
	 *   get    
	 * @param user
	 * @param pass
	 * @return
	 */
	static public String byGetLogin(String user, String pass)
	{
		String path = "http://192.168.0.105/index.php?user="+user+"&pass="+pass;
		try {
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(5000);
			conn.setRequestMethod("GET");
			int code = conn.getResponseCode();
			System.out.println(code);
			if (code == 200) {
				InputStream is = conn.getInputStream();
				String text = Stream.isToString(is);
				return text;
			} else {
				return null;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 *   post    
	 * @param user
	 * @param pass
	 * @return
	 */
	static public String byPostLogin(String user, String pass)
	{
		String path = "http://192.168.0.105/index.php";
		try {
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			String data = "user="+user+"&pass="+pass;
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conn.setRequestProperty("Content-Length", data.length()+"");
			conn.setDoOutput(true);
			OutputStream os = conn.getOutputStream();
			os.write(data.getBytes());
			int code = conn.getResponseCode();
			if (code == 200) {
				InputStream is = conn.getInputStream();
				return Stream.isToString(is); 
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 *   httpclient get   
	 * @param user
	 * @param pass
	 * @return
	 */
	static public String httpClientGetLogin(String user, String pass)
	{
		String path = "http://192.168.0.105/index.php?user="+user+"&pass="+pass;
		try {
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(path);
			HttpResponse response = client.execute(get);
			int code = response.getStatusLine().getStatusCode();
			if (code == 200) {
				InputStream is = response.getEntity().getContent();
				String text = Stream.isToString(is);
				return text;
			}
			return null;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * httpClient post     
	 * @param user
	 * @param pass
	 * @return
	 */
	static public String httpClientPostLogin(String user, String pass)
	{
		String path = "http://192.168.0.105/index.php";
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(path);
		List<NameValuePair> parameters = new ArrayList<NameValuePair>();
		parameters.add(new BasicNameValuePair("user", user));
		parameters.add(new BasicNameValuePair("pass", pass));
		try {
			post.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
			HttpResponse response = client.execute(post);
			int code = response.getStatusLine().getStatusCode();
			if (code == 200) {
				InputStream is = response.getEntity().getContent();
				String text = Stream.isToString(is);
				return text;
			}
			return null;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
}

stream 입력 흐름 을 문자열 로 변환
package com.stream.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class Stream 
{
	/**
	 *            
	 * @param is
	 * @return
	 * @throws IOException
	 */
	static public String isToString(InputStream is) throws IOException
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int len = 0;
		byte[] buffer = new byte[1024];
		while ((len = is.read(buffer)) != -1) {
			baos.write(buffer);
		}
		byte[] result = baos.toByteArray();
		is.close();
		baos.close();
		return new String(result);
	}
}

목록 파일 권한 기억

좋은 웹페이지 즐겨찾기