Android与(Servlet)服务器交互

package com.rocky;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

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

/***
 * @author huangshuhao
 *	思路:
 *		把参数传给一个Uri,当该Uri接受到由post或get方法传过了的
 *		参数后,就交由一个Servlet来处理这些参数,类似网页中处理
 *		一样,都是提交参数后由Servlet来接受并处理
 */

public class LoginActivity extends Activity {
	
	private static final int REQUEST_CODE = 2;
	HttpPost httpRequest=new HttpPost(UriAPI.HTTPCustomer);
	Button loginButton;
	Button cancael;
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main2);
		loginButton=(Button) findViewById(R.id.login);
		//注册监听器对象
		loginButton.setOnClickListener(new OnClickListener(){
			CharSequence username="";
			CharSequence password="";
			public void onClick(View v)
			{
				//准备需要提交的数据,从手机界面抓取下来
				EditText ev_username =(EditText)findViewById(R.id.username);
				username=ev_username.getText();
				EditText ev_password=(EditText)findViewById(R.id.password);
				password=ev_password.getText();
				
				if(! username.equals("")&&! password.equals("")){
					//创建HttpPost 对象,传入一个Uri
					HttpPost httpRequest =new HttpPost (UriAPI.HTTPCustomer);
					//创建参数
					List<NameValuePair> params=new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("username", username.toString()));
					params.add (new BasicNameValuePair("password", password.toString()));
					params.add(new BasicNameValuePair("flag","0"));
					try{
						//设置编码格式
						httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
						
						//提交HttpPost对象和获取服务器HttpResponse响应数据完成
						HttpResponse httpResponse=new DefaultHttpClient().execute(httpRequest);
						
						//获取响应服务器的数据
						if(httpResponse.getStatusLine().getStatusCode()==200)
						{
							//利用字节数组流和包装的绑定技术
							byte[] data = new byte[2048];
							//先把从服务端来的数据转化成字节数组
							data =EntityUtils. toByteArray((HttpEntity)httpResponse.getEntity());
							//再创建字节数组输入流对象
							ByteArrayInputStream bais = new ByteArrayInputStream(data);
							//绑定字节流和数据包装流
							DataInputStream dis = new DataInputStream(bais);
							//将字节数组中的数据还原成原来的各种数据类型,代码如下:
							String user = new String(dis.readUTF());
						}
					}catch(ClientProtocolException e){
						e.printStackTrace();
					}catch(UnsupportedEncodingException e){
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		});
	}
	
	public class UriAPI {
		/** 定义一个Uri **/
		public static final String HTTPCustomer ="http://192.168.157.100:8028/JSHWDemo/servlet/CustomerServlet";
	}
}


服务器端代码

import java.io.DataOutputStream;

public class CustomerServlet extends HttpServlet {
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		response.setContentType(CONTENT_TYPE);
		try{
                        //做登录判断后返回的结果
                        customer = cusDao.login(username,password);
                        DataOutputStream output = new DataOutputStream(response.getOutputStream());
			if(customer! =null){
                                //登录成功,向手机写数据
//				output.writeUTF(customer.getUsername());
				output.writeUTF("服务器端数据:用户名:" + username);
				output.writeUTF("服务器端数据:密码:" + password);
				output.writeInt(1);
				output.close();
			}
			else {
				//登录失败
				output.writeUTF("No");
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}

注释已经很清楚了,看注释吧,如果还不行就看<Android手机访问服务器的一种数据交互方法.pdf>

http://wenku.baidu.com/view/e99cc78ca0116c175f0e4842.html


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值