Android网络提交数据(HttpConnection HttpClient)POST GET方式

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	android:id="@+id/widget38"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	android:orientation="vertical"
	xmlns:android="http://schemas.android.com/apk/res/android">
<EditText
	android:id="@+id/et_username"
	android:layout_width="match_parent"
	android:layout_height="wrap_content"
	android:hint="&#35831;&#36755;&#20837;&#29992;&#25143;&#21517;"
	android:textSize="18sp" />
<EditText
	android:id="@+id/et_password"
	android:layout_width="match_parent"
	android:layout_height="wrap_content"
	android:hint="&#35831;&#36755;&#20837;&#23494;&#30721;"
	android:textSize="18sp" />
<Button
	android:id="@+id/btn_get"
	android:onClick="click"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:layout_weight="1000"
	android:text="GET提交" />
<Button
	android:id="@+id/btn_post"
	android:onClick="click"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:layout_weight="1000"
	android:text="POST提交" />
<Button
	android:id="@+id/btn_get_httpclient"
	android:onClick="click"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:layout_weight="1000"
	android:text="HttpClient Get提交" />
<Button
	android:id="@+id/btn_post_httpclient"
	android:onClick="click"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:layout_weight="1000"
	android:text="HttpClient POST提交" />
</LinearLayout>

 

package com.pas.postdata;

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

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.pas.htmlview.utils.StreamTools;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity
{

	private EditText et_username;
	private EditText et_password;

	private final int SHOWINFO = 0;
	private final int CHANGEUI = 1;

	private Handler handler = new Handler()
	{
		@Override
		public void handleMessage(android.os.Message msg)
		{
			switch (msg.what)
			{
			case SHOWINFO:
				ShowInfo(MainActivity.this, msg.obj.toString());
				break;
			case CHANGEUI:
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		et_username = (EditText) findViewById(R.id.et_username);
		et_password = (EditText) findViewById(R.id.et_password);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public void click(final View view)
	{
		final String username = et_username.getText().toString().trim();
		final String password = et_password.getText().toString().trim();

		if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password))
		{
			Toast.makeText(this, "信息不可为空", Toast.LENGTH_LONG).show();
		} else
		{

			new Thread()
			{
				@Override
				public void run()
				{
					try
					{
						InputStream is = null;
						// GET方式
						if (view.getId() == R.id.btn_get)
						{
							is = getByHttpConnection(username, password);
						} else if (view.getId() == R.id.btn_post)
						{
							is = postByHttpConnection(username, password);
						} else if (view.getId() == R.id.btn_get_httpclient)
						{
							// HttpClient 方式
							is = getByHttpClient(username, password);
						} else if (view.getId() == R.id.btn_post_httpclient)
						{
							is = postByHttpClient(username, password);
						}

						final String res = StreamTools.StreamToString(is);
						if (res != null)
						{
							// 不使用handler的另一种方式
							// 这种方式也可以封装
							runOnUiThread(new Runnable()
							{

								@Override
								public void run()
								{
									ShowInfo(MainActivity.this, res);
								}
							});
						} else
						{
							handler.sendMessage(getMsg(SHOWINFO, "失败"));
						}
					} catch (Exception e)
					{
						e.printStackTrace();
						handler.sendMessage(getMsg(SHOWINFO, "获取失败"));
					}
				}
			}.start();
		}
	}

	private InputStream postByHttpConnection(final String username, final String password) throws MalformedURLException, IOException, ProtocolException
	{
		HttpURLConnection conn;
		// POST方式
		String path = "http://192.168.1.100:8080/ServletTest/Login";
		URL post_url = new URL(path);
		conn = (HttpURLConnection) post_url.openConnection();
		conn.setRequestMethod("POST");

		// 准备数据
		String data = "username=" + username + "&password=" + password;
		byte[] data_bytes = data.getBytes();

		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		conn.setRequestProperty("Content-Length", data_bytes.length + "");
		// POST方式:浏览器将数据以流的方式写入服务器
		conn.setDoOutput(true);// 允许向外部写入数据
		OutputStream os = conn.getOutputStream();
		os.write(data_bytes);
		conn.setConnectTimeout(5000);

		if (200 == conn.getResponseCode())
		{
			return conn.getInputStream();
		}
		return null;
	}

	private InputStream getByHttpConnection(final String username, final String password) throws UnsupportedEncodingException, MalformedURLException, IOException, ProtocolException
	{
		HttpURLConnection conn;
		String path = "http://192.168.1.100:8080/ServletTest/Login" + "?username=" + URLEncoder.encode(username, "utf-8") + "&password=" + URLEncoder.encode(password, "utf-8");
		URL get_url = new URL(path);
		conn = (HttpURLConnection) get_url.openConnection();
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(5000);
		return conn.getInputStream();
	}

	private InputStream getByHttpClient(final String username, final String password) throws Exception
	{
		String path = "http://192.168.1.100:8080/ServletTest/Login" + "?username=" + URLEncoder.encode(username, "utf-8") + "&password=" + URLEncoder.encode(password, "utf-8");
		HttpClient client = new DefaultHttpClient();

		HttpGet httpGet = new HttpGet(path);

		HttpResponse response = client.execute(httpGet);
		if (200 == response.getStatusLine().getStatusCode())
		{
			return response.getEntity().getContent();
		}
		return null;
	}

	private InputStream postByHttpClient(final String username, final String password) throws Exception
	{
		String path = "http://192.168.1.100:8080/ServletTest/Login";
		HttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(path);
		
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("username", username));
		params.add(new BasicNameValuePair("password", password));
		httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
		
		HttpResponse response = client.execute(httpPost);
		if (200 == response.getStatusLine().getStatusCode())
		{
			return response.getEntity().getContent();
		}
		return null;
	}

	public Message getMsg(int what, Object obj)
	{
		Message msg = new Message();
		msg.what = what;
		msg.obj = obj;
		return msg;
	}

	public void ShowInfo(Context context, String info)
	{
		Toast.makeText(context, info, Toast.LENGTH_SHORT).show();
	}
}

 

package com.pas.htmlview.utils;

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

public class StreamTools
{

	public static String StreamToString(InputStream is)
	{
		try
		{
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int len = 0;
			byte[] buffer = new byte[1024];
			while ((len = is.read(buffer)) != -1)
			{
				baos.write(buffer, 0, len);
			}
			is.close();
			baos.close();
			byte[] res = baos.toByteArray();
			String tem=new String(res);
			return new String(res);
		} catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}
}

 

你可能感兴趣的:(Android网络提交数据(HttpConnection HttpClient)POST GET方式)