Android客户端和服务器通信

一直很好奇,android是如何和后台通信的,我一直觉得android通信是否和j2ee一样给一个url就可以了;后来在网络上找各种资料脑补,才发现通信方式和j2ee的url大相庭径,于是恶补之..

说到底,android和服务器通信,使用了HTTP协议的方式,在本机编写客户端和服务器,其中的ip地址就是路由器分配的地址比如:http:x.x.x.x./x。于是自己看了一些视频,记录一下学习笔记

在server端使用servet来做后台,并且分为doGet和doPost,实现简单的后台数据回传,代码如下:

public class AndroidResponse extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//获取andoird客户端请求的数据
		String name=req.getParameter("username");
		String pwd=req.getParameter("password");
		System.out.println("username="+name);
		System.out.println("password="+pwd);
		
		if("admin".equals(name)&&"123".equals(pwd)){
			resp.getOutputStream().write("登陆成功".getBytes("UTF-8"));
		}else{
			resp.getOutputStream().write("登陆失败".getBytes("UTF-8"));
		}
		//调用doPost
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
	}
	@Override
	public void init() throws ServletException {
		super.init();
	}
	@Override
	public void destroy() {
		super.destroy();
	}
}
后台简单实现之后,现在开始编写客户端

public class RequestActivity extends Activity {
	private EditText in_username;
	private EditText in_password;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		in_username = (EditText) findViewById(R.id.in_username);
		in_password = (EditText) findViewById(R.id.in_password);
		//给Get按钮绑定事件
		findViewById(R.id.Getbutton).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				final String name = in_username.getText().toString().trim();
				final String pwd = in_password.getText().toString().trim();
				// 提交、验收数据都放在子线程中执行
				new Thread() {
					public void run() {
						final String result = ChecKService.checkGet(name, pwd);
						if (result != null) {
							runOnUiThread(new Runnable() {
								public void run() {
									Toast.makeText(RequestActivity.this,
											result, 0).show();
								}
							});
						} else {
							// 请求失败
							Toast.makeText(RequestActivity.this, "请求失败", 0)
									.show();
						}
					};
				}.start();
			}
		});
		//给post按钮绑定事件
		findViewById(R.id.Postbutton).setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				final String name = in_username.getText().toString().trim();
				final String pwd = in_password.getText().toString().trim();
				// 提交、验收数据都放在子线程中执行
				new Thread() {
					public void run() {
						final String result = ChecKService.checkGet(name, pwd);
						if (result != null) {
							runOnUiThread(new Runnable() {
								public void run() {
									Toast.makeText(RequestActivity.this,
											result, 0).show();
								}
							});
						} else {
							// 请求失败
							Toast.makeText(RequestActivity.this, "请求失败", 0)
									.show();
						}
					};
				}.start();
			}
		});
	}
}
上面使用到了CheckService类,如下是代码:

public class ChecKService {
	public static String checkGet(String username, String password) {
		try {
			String path = "http://192.168.1.100:8080/Android_Server/AndroidResponse?username="
					+ username + "&password=" + password;
			URL url = new URL(path);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setConnectTimeout(5000);
			// 设置请求方式
			connection.setRequestMethod("GET");

			// 获取服务器返回的数据
			int code = connection.getResponseCode();
			if (code == 200) {
				// 请求成功,响应服务器返回的数据
				InputStream inputStream = connection.getInputStream();
				// 解析服务器返回的数据
				String text = StringUtils.rendeInputStream(inputStream);
				return text;
			} else {
				// 请求失败
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	//post方式提交
	public static String checkPost(String username, String password) {
		try {
			//请求服务器地址
			String path = "http://192.168.1.100:8080/Android_Server/AndroidResponse";
			URL url = new URL(path);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			//超时时间
			connection.setConnectTimeout(5000);
			// 设置请求方式
			connection.setRequestMethod("POST");
			//准备数据 post请求格式
			String data="username="+username+"&password"+password;
			connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			connection.setRequestProperty("Content-Length",data.length()+"");
			
			//post用流的方式发送给服务器
			connection.setDoInput(true);
			OutputStream os=connection.getOutputStream();
			os.write(data.getBytes());
			// 获取服务器返回的数据
			int code = connection.getResponseCode();
			if (code == 200) {
				// 请求成功,响应服务器返回的数据
				InputStream inputStream = connection.getInputStream();
				// 解析服务器返回的数据
				String text = StringUtils.rendeInputStream(inputStream);
				return text;
			} else {
				// 请求失败
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
实现效果之后,发现使用HTTP方式让android和服务器通信,自己要做很多底层的事情,有什么框架或者工具之类的可以减少这种工作量呢?


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值