一。服务器
1.访问配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>WatchLogin</servlet-name> <servlet-class>com.cuiweiyou.servlets.WatchLogin</servlet-class> </servlet> <servlet-mapping> <servlet-name>WatchLogin</servlet-name> <url-pattern>/servlets/WatchLogin</url-pattern> </servlet-mapping> </web-app> |
2.请求处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
public class WatchLogin extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); String name = request.getParameter("username"); String pswd = request.getParameter("password"); // GET访问时,须转码 name = new String(name.getBytes("iso8859-1"), "utf-8"); pswd = new String(pswd.getBytes("iso8859-1"), "utf-8"); System.out.println("用户:" +name + "\t密码:" + pswd); // 默认使用iso8859-1编码输出,如果码表没有输出的字符,则使用当前系统编码GBK。指定为utf-8 response.getOutputStream().write(("GET反馈:你的名字:" + name + ", 密码:" + pswd).getBytes("utf-8")); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); String name = request.getParameter("username"); String pswd = request.getParameter("password"); System.out.println("用户:" +name + "\t密码:" + pswd); // 默认使用iso8859-1编码输出,如果码表没有输出的字符,则使用当前系统编码GBK。指定为utf-8 response.getOutputStream().write(("POST反馈:你的名字:" + name + ", 密码:" + pswd).getBytes("utf-8")); } } |
二。客户端
1.权限
1 2 3 |
<uses-permission android:name="android.permission.INTERNET"/> |
2.布局
3.工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
public class NetUtils { private static final String TAG = "NetUtils"; // 本机搭建的服务器localhost在模拟器中的路径未10.0.2.2 private static final String TO_URI = "http://10.0.2.2:8080//ForAndroid/servlets/WatchLogin?"; /** * 使用get的方式登录 */ public static String loginOfGet(String userName, String password) { HttpURLConnection conn = null; try { String data = "username=" + URLEncoder.encode(userName) + "&password=" + URLEncoder.encode(password); URL url = new URL(TO_URI + data); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); // get或者post必须得全大写 conn.setConnectTimeout(10000); // 连接的超时时间 conn.setReadTimeout(5000); // 读数据的超时时间 int responseCode = conn.getResponseCode(); if (responseCode == 200) { InputStream is = conn.getInputStream(); String state = getStringFromInputStream(is); return state; } else { Log.i(TAG, "访问失败: " + responseCode); } } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); // 关闭连接 } } return null; } /** * Post方法提交 */ public static String loginOfPost(String userName, String password) { HttpURLConnection conn = null; try { URL url = new URL(TO_URI); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); // 必须是全大写的POST conn.setConnectTimeout(5000); // 连接超时 conn.setReadTimeout(5000); // 读取超时 conn.setDoOutput(true); // 是否从httpUrlConnection读入, 允许输出 // conn.setRequestProperty("Content-Length", 234); // 设置请求头消息, // 可以设置多个 // post请求的参数 String data = "username=" + userName + "&password=" + password; // 获得一个输出流, 用于向服务器写数据, 默认情况下, 系统不允许向服务器输出内容 OutputStream out = conn.getOutputStream(); out.write(data.getBytes()); out.flush(); out.close(); int responseCode = conn.getResponseCode(); if (responseCode == 200) { InputStream is = conn.getInputStream(); String state = getStringFromInputStream(is); return state; } else { Log.i(TAG, "访问失败: " + responseCode); } } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); } } return null; } /** * 根据流返回一个字符串信息 */ private static String getStringFromInputStream(InputStream is) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = -1; while ((len = is.read(buffer)) != -1) { baos.write(buffer, 0, len); } is.close(); // 把流中的数据转换成字符串, 采用的编码是: utf-8 String html = baos.toString(); baos.close(); return html; } } |
4.主程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
public class MainActivity extends ActionBarActivity { private EditText etUserName; private EditText etPassword; private String userName; private String password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etUserName = (EditText) findViewById(R.id.et_username); etPassword = (EditText) findViewById(R.id.et_password); userName = etUserName.getText().toString(); password = etPassword.getText().toString(); } public void doGet(View v) { new Thread(new Runnable() { @Override public void run() { // 使用get方式抓去数据 final String state = NetUtils.loginOfGet(userName, password); // 此方法在主线程中执行 runOnUiThread(new Runnable() { @Override public void run() { // 就是在主线程中弹出一个提示 Toast.makeText(MainActivity.this, state, 0).show(); } }); } }).start(); } public void doPost(View v) { new Thread(new Runnable() { @Override public void run() { final String state = NetUtils.loginOfPost(userName, password); // 执行任务在主线程中 runOnUiThread(new Runnable() { @Override public void run() { // 就是在主线程中操作 Toast.makeText(MainActivity.this, state, 0).show(); } }); } }).start(); } } |
三。使用android-async-http简化请求
此时代码量锐减,不使用工具类。
1.下载:[download id="185"]
2.将%android-async-http-master%/library/src/main/java下的com包放入工程

3.主程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
public class MainActivity2 extends ActionBarActivity { // https://github.com/loopj/android-async-http // https://github.com/loopj/android-async-http/archive/master.zip // 控件 private EditText etUserName; private EditText etPassword; // 用户名和密码 private String userName; private String password; // 请求路径 private String LOG_URI = "http://10.0.2.2:8080//ForAndroid/servlets/WatchLogin"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etUserName = (EditText) findViewById(R.id.et_username); etPassword = (EditText) findViewById(R.id.et_password); userName = etUserName.getText().toString(); password = etPassword.getText().toString(); } /** * GET请求 */ public void doGet(View v) { // 1.创建异步连接Http客户端 AsyncHttpClient client = new AsyncHttpClient(); // 2.请求数据 String data = "username=" + URLEncoder.encode(userName) + "&password=" + URLEncoder.encode(password); // 3.发送数据(uri,请求响应) client.get(LOG_URI + "?" + data, new MyResponseHandler()); } /** * POST请求 */ public void doPost(View v) { // 1.创建异步连接Http客户端 AsyncHttpClient client = new AsyncHttpClient(); // 2.请求数据 RequestParams params = new RequestParams(); params.put("username", userName); params.put("password", password); // 3.发送数据(uri,数据,请求响应) client.post(LOG_URI, params, new MyResponseHandler()); } /** * 响应请求的处理 */ class MyResponseHandler extends AsyncHttpResponseHandler { // 请求成功的处理 public void onSuccess(int statusCode, org.apache.http.Header[] headers, byte[] responseBody) { Toast.makeText( MainActivity2.this, "成功: statusCode: " + statusCode + ", body: \n" + new String(responseBody), 0).show(); } // 请求失败的处理 public void onFailure(int statusCode, org.apache.http.Header[] headers, byte[] responseBody, Throwable error) { Toast.makeText(MainActivity2.this, "失败: statusCode: \n" + statusCode, 0).show(); } } } |

声明
本文由崔维友 威格灵 cuiweiyou vigiles cuiweiyou 原创,转载请注明出处:http://www.gaohaiyan.com/177.html
承接App定制、企业web站点、办公系统软件 设计开发,外包项目,毕设