Android笔记 采用httpclient提交数据到服务器demo

本例建立在上篇日志基础之上web端代码不变

布局文件增加了两个按钮

httpclient相对于普通get post提交方式优势在于不需手动指定传输的编码集 避免了乱码

</pre><pre name="code" class="html"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/et_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入用户名"
        android:text="张三" >
    </EditText>

    <EditText
        android:id="@+id/et_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入密码"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="登录" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click2"
        android:text="post登录" />

    <strong><Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click3"
        android:text="clientget登录" />

    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click4"
        android:text="clientpost登录" /></strong>

</LinearLayout>
service层多了两个方法

package com.example.a54_senddatatoservice.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
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.ClientProtocolException;
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.example.a54_senddatatoservice.utils.StreamTools;

public class LoginService {
	/**
	 * 
	 * @param username
	 * @param password
	 * @return null---->error text--->success
	 */
	public static String loginByGet(String username, String password) {
		// 提交数据到服务器
		// 拼装路径

		try {
			String path = "http://10.10.5.31:8080/web/LoginServlet?username="
					+ URLEncoder.encode(username, "UTF-8") + "&password="
					+ password;
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			conn.setRequestMethod("GET");
			int code = conn.getResponseCode();
			if (code == 200) {
				// 请求成功
				InputStream is = conn.getInputStream();
				String text = StreamTools.readInputStream(is);
				return text;

			} else {
				return null;
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * @param username
	 * @param password
	 * @return null---->error text--->success
	 */
	public static String loginByPost(String username, String password) {
		// 提交数据到服务器
		// 拼装路径

		try {
			String path = "http://10.10.5.31:8080/web/LoginServlet";
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			conn.setRequestMethod("POST");
			// 准备数据
			String data = "username=" + URLEncoder.encode(username, "UTF-8")
					+ "&password=" + password;
			conn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			conn.setRequestProperty("Content-Length", data.length() + "");

			// post实际上是浏览器把数据写给了服务器
			conn.setDoOutput(true);// UrlConnection允许向外传数据
			OutputStream os = conn.getOutputStream();
			os.write(data.getBytes());
			int code = conn.getResponseCode();
			if (code == 200) {
				// 请求成功
				InputStream is = conn.getInputStream();
				String text = StreamTools.readInputStream(is);
				return text;

			} else {
				return null;
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	<strong>/**
	 * 采用HTTPclient get提交数据
	 * 
	 * @param username
	 * @param password
	 * @return null---->error text--->success
	 */
	public static String loginByClientGet(String username, String password) {
		// 1 open browser
		HttpClient client = new DefaultHttpClient();
		String path = null;
		try {
			path = "http://10.10.5.31:8080/web/LoginServlet?username="
					+ URLEncoder.encode(username, "UTF-8") + "&password="
					+ password;
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 2 enter an address
		HttpGet httpGet = new HttpGet(path);

		// 3 敲回车
		try {
			client.execute(httpGet);
			HttpResponse response = client.execute(httpGet);
			// 状态行 其中有状态码
			int code = response.getStatusLine().getStatusCode();
			if (code == 200) {
				// 请求成功
				InputStream is = response.getEntity().getContent();
				String text = StreamTools.readInputStream(is);
				return text;

			} else {
				return null;
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

	}

	/**
	 * 采用HTTPclient post提交数据
	 * 
	 * @param username
	 * @param password
	 * @return null---->error text--->success
	 */
	public static String loginByClientPost(String username, String password) {
		try {
			//1 open browser
			HttpClient client = new DefaultHttpClient();
			//2 enter address
			String path = "http://10.10.5.31:8080/web/LoginServlet";
			HttpPost httpPost = new HttpPost(path);
			//指定要提交的数据实体                      参数         编码
			List<NameValuePair> parameters =new ArrayList<NameValuePair>();
			parameters.add(new BasicNameValuePair("username", username));
			parameters.add(new BasicNameValuePair("password", password));
			httpPost.setEntity(new UrlEncodedFormEntity(parameters, "utf-8"));
			//3 敲回车
			HttpResponse  httpResponse= client.execute(httpPost);
			int code = httpResponse.getStatusLine().getStatusCode();
			if (code == 200) {
				// 请求成功
				InputStream is = httpResponse.getEntity().getContent();
				String text = StreamTools.readInputStream(is);
				return text;

			} else {
				return null;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
		
		
	}</strong>
}
主界面多了两个点击事件

package com.example.a54_senddatatoservice;

import com.example.a54_senddatatoservice.service.LoginService;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
	// 要配合web项目 目录位于E:\study\soft\Android\gaobo\android\web
	private EditText et_username;
	private EditText et_password;

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

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

		new Thread() {
			public void run() {
				final String result = LoginService.loginByGet(username,
						password);
				if (result != null) {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							// TODO Auto-generated method stub
							Toast.makeText(MainActivity.this, result,
									Toast.LENGTH_SHORT).show();
						}
					});
				} else {
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							Toast.makeText(MainActivity.this, "请求失败",
									Toast.LENGTH_SHORT).show();
						}
					});
				}
			};
		}.start();

	}

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

		new Thread() {
			public void run() {
				final String result = LoginService.loginByPost(username,
						password);
				if (result != null) {
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							Toast.makeText(MainActivity.this, result,
									Toast.LENGTH_SHORT).show();
						}
					});
				} else {
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							Toast.makeText(MainActivity.this, "请求失败",
									Toast.LENGTH_SHORT).show();
						}
					});
				}
			};
		}.start();

	}
	
	
	
	
	<strong>public void click3(View view) {
		final String username = et_username.getText().toString().trim();
		final String password = et_password.getText().toString().trim();

		new Thread() {
			public void run() {
				final String result = LoginService.loginByClientGet(username,
						password);
				if (result != null) {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							// TODO Auto-generated method stub
							Toast.makeText(MainActivity.this, result,
									Toast.LENGTH_SHORT).show();
						}
					});
				} else {
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							Toast.makeText(MainActivity.this, "请求失败",
									Toast.LENGTH_SHORT).show();
						}
					});
				}
			};
		}.start();

	}

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

		new Thread() {
			public void run() {
				final String result = LoginService.loginByClientPost(username, password);
				if (result != null) {
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							Toast.makeText(MainActivity.this, result,
									Toast.LENGTH_SHORT).show();
						}
					});
				} else {
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							Toast.makeText(MainActivity.this, "请求失败",
									Toast.LENGTH_SHORT).show();
						}
					});
				}
			};
		}.start();

	}</strong>
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值