Android请求服务器常用方式

最近在学习Android和服务器的请求,觉得有必要记录一下,防止自己忘记

Andriod和服务器通信,一般使用Http协议,Http协议请求方式包括:GET、POST这两种方式;还有就是使用webservice的方式(不再这篇范围之类)

在服务器端,使用servelt来接受传递过来的参数:

public class LoginServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String name=request.getParameter("name");
		String pwd=request.getParameter("pwd");
		
		if("admin".equals(name)&&"admin".equals(pwd)){
			response.getOutputStream().write("login success".getBytes());
		}else{
			response.getOutputStream().write("login error".getBytes());
		}
	}
}


下面开始使用HTTP的Get方式编写代码和服务器请求:

req_btn_get.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				final String name = req_et_name.getText().toString().trim();
				final String pwd = req_et_pwd.getText().toString().trim();
				// 用一个线程来登录
				new Thread() {
					@Override
					public void run() {
						final String resu = RequestServerService.RequestGet(
								name, pwd);
						if (resu != null) {
							runOnUiThread(new Runnable() {

								@Override
								public void run() {
									Toast.makeText(RequestServerActivity.this,
											resu, 0).show();
								}
							});
						} else {
							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									Toast.makeText(RequestServerActivity.this,
											"请求失败", 0).show();
								}
							});
						}
					};
				}.start();
			}
		});
其中使用到了RequestServerService这个类的RequestGet方法,这个类是是一个工具类,主要是把封装请求,代码如下:

public static String RequestGet(String name, String pwd) {
		String path = "http://192.168.4.111:8080/AndroidServer/server?name="
				+ name + "&pwd=" + pwd;
		try {
			URL url = new URL(path);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setConnectTimeout(5000);
			connection.setRequestMethod("GET");
			if (connection.getResponseCode() == 200) {
				InputStream is = connection.getInputStream();
				String result = StreamUtils.readInputStream(is);
				return result;
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
Get方式请求服务器有一个不爽的地方是,如果请求的参数多了就需要不断的拼凑在请求URL的后面,很容易出现问题,可以使用POST的方式请求服务器,代码如下:

public static String RequestPost(String name, String pwd) {
		String path = "http://192.168.4.111:8080/AndroidServer/server";
		String data = "name=" + name + "&pwd=" + pwd;
		try {
			URL url = new URL(path);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setReadTimeout(5000);
			connection.setRequestMethod("POST");
			// 设置POST必须的属性
			connection.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			connection.setRequestProperty("Content-Length", data.length() + "");
			// 把数据写给服务器
			connection.setDoInput(true);
			OutputStream os = connection.getOutputStream();
			os.write(data.getBytes());
			if (connection.getResponseCode() == 200) {
				InputStream is = connection.getInputStream();
				String result = StreamUtils.readInputStream(is);
				return result;
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
细心的一定发现还是用了一个工具类StreamUtils,这个类主要就是把的到的inputStream请求解析出来,代码如下:

public static String readInputStream(InputStream is) {
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int leng = 0;
			while ((leng = is.read(buffer)) != -1) {
				baos.write(buffer, 0, leng);
			}
			is.close();
			baos.close();
			byte[] temp = baos.toByteArray();
			String result = new String(temp);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "解析失败";
	}
使用HTTP的POST或者GET都发现要写的代码很多,并且很多都是底层的,并未对其封装或者抽象。android系统本身对Apache的HttpClient进行了封装,直接调用即可代码结构如下:

GET方式如下:

public static String HttpClientGet(String name, String pwd) {
		try {
			String path = "http://192.168.4.111:8080/AndroidServer/server?name="
					+ URLEncoder.encode(name)
					+ "&pwd="
					+ URLEncoder.encode(pwd);
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(path);
			HttpResponse httpResponse = client.execute(get);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				InputStream is = httpResponse.getEntity().getContent();
				String result = StreamUtils.readInputStream(is);
				return result;
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
POST方式如下:

public static String HttpClientPost(String name, String pwd) {
		try {
			String path = "http://192.168.4.111:8080/AndroidServer/server";
			HttpClient client = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(path);
			// 指定要提交的数据
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			list.add(new BasicNameValuePair("name", name));
			list.add(new BasicNameValuePair("pwd", pwd));
			httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
			HttpResponse httpResponse = client.execute(httpPost);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				InputStream is = httpResponse.getEntity().getContent();
				String result = StreamUtils.readInputStream(is);
				return result;
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
写完代码之,发现虽然使用Apache的HttpClent,但是写代码好像还是很多。如果关注过Git的一定知道有AsyncHttp这个开源项目,这个项目是再一次对Apache的HttpClient进行封装,在代码编写上和理解上比较容易,代码结果如下:

AsyncHttp的GET方式请求:

final String name = req_et_name.getText().toString().trim();
				final String pwd = req_et_pwd.getText().toString().trim();
				String url="http://192.168.4.111:8080/AndroidServer/server";
				AsyncHttpClient asyncHttpClient=new AsyncHttpClient();
				RequestParams params=new RequestParams();
				params.put("name", name);
				params.put("pwd", pwd);
				asyncHttpClient.get(url, new AsyncHttpResponseHandler() {
					
					@Override
					public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
						
					}
					
					@Override
					public void onFailure(int statusCode, Header[] headers,
							byte[] responseBody, Throwable error) {
						
					}
				});
POST也一样,只是变了请求方式。

总结:学习了请求各种方式之后发现,各种请求方式都有自身的优势,只是针对各种使用场景不同而已。







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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值