网络请求:get、post、httpclient-get、httpclient-post
安卓客户端通过各种网络请求方式将用户名和密码提交到自己编写的本地java后台,后台通过Servlet获取网络提交的数据,判断是否跟原先设置好的用户名和密码一致。
以下是安卓客户端的Demo显示界面:
布局文件:
<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="com.csh.form.MainActivity" > <EditText android:id="@+id/et_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="用户名"/> <EditText android:id="@+id/et_pass" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="密码"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="get请求登录" android:onClick="login"/> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="post请求登录" android:onClick="postLogin"/> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="HttpClient--Get" android:onClick="HttpClientGet" /> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="HttpClient--Post" android:onClick="HttpClientPost" /></LinearLayout>Android实现各种网络请求代码:/*** get请求* @param v*/public void login(View v) { name = et_name.getText().toString(); pass = et_pass.getText().toString(); Thread thread = new Thread() { @Override public void run() { super.run(); String path = "http://192.168.0.103:8099/RegesterServlet/RegesterServlet?username=" + URLEncoder.encode(name) + "&passWord=" + pass; try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(8 * 1000); conn.setReadTimeout(8 * 1000); System.out.PRintln("测试--1"); conn.connect(); System.out.println("测试--2"); if (conn.getResponseCode() == 200) { //请求成功 InputStream is = conn.getInputStream(); String text = HttpTools.getText(is); System.out.println(text); Message msg = handler.obtainMessage(); msg.obj = text; msg.what = 1; handler.sendMessage(msg); } else { //请求失败 System.out.println("请求失败"); } } catch (Exception e) { e.printStackTrace(); System.out.println(e); } } }; thread.start();} /** * post请求 * @param v */ public void postLogin(View v) { name = et_name.getText().toString(); pass = et_pass.getText().toString(); Thread thread = new Thread() { @Override public void run() { super.run(); String path = "http://192.168.0.103:8099/RegesterServlet/RegesterServlet"; try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(8 * 1000); conn.setReadTimeout(8 * 1000); //添加post请求头中自动添加的属性 //流里的数据的mimetype conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); String content = "username=" + URLEncoder.encode(name) + "&password=" + pass; //流里数据的长度 conn.setRequestProperty("Content-Length", content.length() + ""); //打开连接对象的输出流 conn.setDoOutput(true); //获取连接对象的输出流 OutputStream os = conn.getOutputStream(); //把数据写入到输出流中 os.write(content.getBytes()); if (conn.getResponseCode() == 200) { InputStream is = conn.getInputStream(); String text = HttpTools.getText(is); Message msg = handler.obtainMessage(); msg.obj = text; msg.what = 1; handler.sendMessage(msg); } } catch (Exception e) { e.printStackTrace(); } } }; thread.start(); } /** * httpClient -- get请求 * @param v */ public void HttpClientGet(View v) { name = et_name.getText().toString(); pass = et_pass.getText().toString(); Thread thread = new Thread() { @Override public void run() { super.run(); String path = "http://192.168.0.103:8099/RegesterServlet/RegesterServlet?username=" + URLEncoder.encode(name) + "&password=" + pass; try { //1、创建client对象 HttpClient client = new DefaultHttpClient(); //2、创建get请求对象 HttpGet get = new HttpGet(path); //3、使用client发送get请求 HttpResponse response = client.execute(get); //4、获取状态行 StatusLine line = response.getStatusLine(); //5、获取状态码 int statusCode = line.getStatusCode(); if (statusCode == 200) { //6、获取实体 HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); String text = HttpTools.getText(is); Message msg = handler.obtainMessage(); msg.obj = text; msg.what = 1; handler.sendMessage(msg); } } catch (Exception e) { e.printStackTrace(); } } }; thread.start(); } /** * httpClient -- post请求 * @param v */ public void HttpClientPost(View v) { name = et_name.getText().toString(); pass = et_pass.getText().toString(); Thread thread = new Thread() { @Override public void run() { super.run(); String path = "http://192.168.0.103:8099/RegesterServlet/RegesterServlet"; //1、创建client对象 HttpClient client = new DefaultHttpClient(); //2、创建post请求对象 HttpPost post = new HttpPost(path); //3、把要提交的数据封装至post中----创建实体对象 List<NameValuePair> parameters = new ArrayList<NameValuePair>(); BasicNameValuePair bnvp1 = new BasicNameValuePair("username", name); BasicNameValuePair bnvp2 = new BasicNameValuePair("password", pass); parameters.add(bnvp1); parameters.add(bnvp2); try { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8"); //4、把实体对象封装至post对象中 post.setEntity(entity); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } try { //5、使用client发送post请求 HttpResponse response = client.execute(post); //6、获取状态行 StatusLine line = response.getStatusLine(); //7、获取状态码 int code = line.getStatusCode(); if (code == 200) { //8、获取实体 HttpEntity entity = response.getEntity(); //获取输入流 InputStream is = entity.getContent(); String text = HttpTools.getText(is); Message msg = handler.obtainMessage(); msg.obj = text; msg.what = 1; handler.sendMessage(msg); } } catch (Exception e) { e.printStackTrace(); } } }; thread.start(); }Java实现的后台Servlet代码如下:@WebServlet("/RegesterServlet")public class RegesterServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public RegesterServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //response.getWriter().append("Served at: ").append(request.getContextPath()); String username = request.getParameter("username"); String password = request.getParameter("password"); System.out.println(username + " : " + password); System.out.println("-----------------------------------"); ServletOutputStream os = response.getOutputStream(); if (username.equals("qwe") && password.equals("123")) { os.write("登录成功".getBytes()); System.out.println("---------------登陆成功----------------"); } else { os.write("登录失败!!!".getBytes()); System.out.println("---------------登陆失败----------------"); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); }}Android客户端中网络请求的链接可以现在网页中测试,写一个form表单,实现get和post请求,然后在地址栏copy链接,进而在Android中实现相对应的网络请求,以下是表单的代码:<body> <form action="RegesterServlet" method="post"> Username: <input type="text" name="username"> <br> Password: <input type="password" name="password"> <br> <input type="submit" value="Login"> </form> <br> </body>表单中的post请求只需要将上面method改成post即可。
新闻热点
疑难解答