Android复习练习十四(客户端账户登陆服务端)

需求:写一个Android客户端,输入用户名和密码,分别可以使用get和post方式发送请求来登陆Tomcat下的服务端,而后可以通过服务端发送回来的数据来显示是登陆成功还是失败。

基本流程:

1、在新线程中来启动连接方法,得到GET或POST方法相对应的正确URL对象

2、通过URL得到对应的连接对象HttpURLConnection实例connection

3、设置connection的属性,比如请求超时和连接超时时间,设置是采用GET还是POST方式发出请求,如果是POST方式,则还需要得到connection的输出流,然后通过输出流将用户名和密码方式发送给服务端

4、使用connection进行连接,并获取连接返回的响应码responseCode,如果responseCode/100==2,那么说明连接成功

5、连接成功的条件 下,获取connection的输入流,从输入流读取服务端发回的状态字符串,并返回给主线程

6、主线程从得到的字符串数据来判断后续的操作

7、最后需要在清单文件中添加Internet权限


虽然不难,但是还是有许多细节需要注意的:


(1)在以GET方式来发送请求的时候,用户名username和密码password都是使用URL方式来发送的,那么发送过程之中会采用URL编码,如果不对应的话,服务端得到的username和password就会是一大堆?乱码,所以在此之前需要将username和password进行URL编码:

username = URLEncoder.encode(username,"UTF-8");

password = URLEncoder.encode(password,"UTF-8");


(2)其次就是在使用POST方式发送的时候,需要设置一个发送的编码,使用http请求头的方式:

connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=utf-8");

connection.setRequestProperty("Content-Type",这里有一个不太明白的地方,就是为什么MIME-Type要设置成 application/x-www-form-urlencoded才行,我试过别的,比如text/html之类的都不行,服务器都无法识别发送过去的用户名和密码,返回来的信息也是乱码,这里留作以后继续研究

(3)还有就是如果服务端发送过来的字节数据byte[],如果是默认采用原本是采用ISO8859-1的字符串再.getBytes()方法发送过来的话,那么使用inputstream接收的时候如果需要转化成字符串的话也需要进行编码转换:new String(bytes,"UTF-8")

代码如下:
Activity

package com.alexchen.qqclient;


import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


import com.alexchen.qqclient.utils.NetUtils;


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;


public class MainActivity extends Activity {


protected static final int CONNECTION_FAIL = 0;
private static final int ENCODING_ERROR = 1;
private static final int URLPARSING_ERROR = 2;
private EditText et_username;
private EditText et_password;
private String username;
private String password;
private Handler handler = new Handler() {


@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case CONNECTION_FAIL:
Toast.makeText(MainActivity.this, "连接网络失败,请重试", 0).show();


break;
case ENCODING_ERROR:
Toast.makeText(MainActivity.this, "编码选择错误", 0).show();


break;
case URLPARSING_ERROR:
Toast.makeText(MainActivity.this, "URL解析错误", 0).show();


break;


default:
break;
}
}


};


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_username = (EditText) findViewById(R.id.et_username);
et_password = (EditText) findViewById(R.id.et_password);
}


public void loginGet(View view) throws IOException {
username = et_username.getText().toString().trim();
password = et_password.getText().toString().trim();
new Thread(new Runnable() {


@Override
public void run() {
final String status = NetUtils.loginOfGet(username, password,
MainActivity.this);
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, status, 0).show();
}
});
}
}).start();
}


public void loginPost(View view) {
username = et_username.getText().toString().trim();
password = et_password.getText().toString().trim();
new Thread(new Runnable() {
@Override
public void run() {
final String status = NetUtils.loginOfPost(username, password,
MainActivity.this);
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, status, 0).show();
}
});
}
}).start();
}
}



NetUtils连接工具类

package com.alexchen.qqclient.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;


import android.content.Context;


import com.alexchen.qqclient.R;


public class NetUtils {


protected static final int CONNECTION_FAIL = 0;
protected static final int CONNECTION_SUCCESS = 1;
protected static final String ENCODING = "UTF-8";
private static final int ENCODING_ERROR = 1;
private static final int URLPARSING_ERROR = 2;
private static HttpURLConnection connection;
private static String status;
private static InputStream is;


public static String loginOfGet(String username, String password,
Context context) {
try {
String data = "?username=" + URLEncoder.encode(username, ENCODING)
+ "&password=" + URLEncoder.encode(password, ENCODING);
URL url = new URL(context.getString(R.string.serverurl) + data);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
// connection.setDoOutput(true);//POST方法必须设置这个,因为POST方法是用流来传输数据的
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode / 100 == 2) {
is = connection.getInputStream();


int len = -1;
byte[] buffer = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((len = is.read(buffer)) != -1) {
baos.write(buffer);
}
status = baos.toString();
if (baos != null) {
baos.close();
}


if (is != null) {
is.close();
}
return status;


} else {
// 连接失败
return String.valueOf(responseCode);


}


} catch (UnsupportedEncodingException e) {
// 不支持的编码格式
e.printStackTrace();
// return String.valueOf(ENCODING_ERROR);
} catch (MalformedURLException e) {
// URL解析出错
e.printStackTrace();
// return String.valueOf(URLPARSING_ERROR);
} catch (IOException e) {
// 网络连接建立失败
e.printStackTrace();
// return String.valueOf(CONNECTION_FAIL);
} finally {
// 断开连接
if (connection != null) {
connection.disconnect();
}
}


return "连接失败";


}


public static String loginOfPost(String username, String password,
Context context) {
try {
String data = "username=" + username + "&" + "password=" + password;
URL url = new URL(context.getString(R.string.serverurl));
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);// post方法必须要设置这个
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=utf-8");


connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
OutputStream os = connection.getOutputStream();
os.write(data.getBytes());
os.flush();
os.close();
int responseCode = connection.getResponseCode();
if (responseCode / 100 == 2) {
// 连接成功
is = connection.getInputStream();
int len = -1;
byte[] buffer = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((len = is.read(buffer)) != -1) {
baos.write(buffer);
}
status = baos.toString();
if (is != null) {
is.close();
}
if (baos != null) {
baos.close();
}
return status;
} else {
return "连接失败,responseCode=" + responseCode;
}


} catch (MalformedURLException e) {
// URL出错
e.printStackTrace();
} catch (IOException e) {
// 连接出错
e.printStackTrace();
}


return "连接失败";
}


}


layout布局文件:

<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="${relativePackage}.${activityClass}" >


    <EditText
        android:id="@+id/et_username"
        android:layout_width="fill_parent"
        android:layout_height="40dp"
        android:hint="请输入账号"
        android:padding="5dp"
        android:singleLine="true" />




    <EditText
        android:id="@+id/et_password"
        android:layout_width="fill_parent"
        android:layout_height="40dp"
        android:hint="请输入密码"
        android:padding="5dp"
        android:password="true"
        android:singleLine="true" />


    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="loginGet"
        android:text="GET方式登陆" />


    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="loginPost"
        android:text="POST登陆" />


</LinearLayout>

   



服务端使用简单的Servlet:

package com.alexchen.servlet;


import java.io.IOException;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class LoginServlet extends HttpServlet {


private static final String ENCODING = "UTF-8";


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("这里是doGet");
request.setCharacterEncoding(ENCODING);
response.setContentType(ENCODING);
response.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");// getParameter采用的编码是iso8859-1
String password = request.getParameter("password");
System.out.println("姓名:" + username);
System.out.println("密码:" + password);
System.out.println("===================");
if (username == null || username == "") {
System.out.println("用户名为空,return");
return;
}
if (password == null || password == "") {
System.out.println("密码为空,return");
return;
}


// 采用iso8859-1的编码对姓名进行你转,转换成字节数组,在使用utf-8编码对数据进行编码生成新字符串
//username = new String(username.getBytes("iso8859-1"), "GBK");
//password = new String(password.getBytes("iso8859-1"), "GBK");

username = new String(username.getBytes(ENCODING), ENCODING);//这里我发现我的服务器默认是UTF-8,所以不需要做转换
password = new String(password.getBytes(ENCODING), ENCODING);


System.out.println("姓名:" + username);
System.out.println("密码:" + password);


if ("李四".equals(username) && "123".equals(password)) {
// 默认情况下,使用iso8859-1的编码,但这里是中文,如果发现码表中没有这些字符的编码,则使用当前系统的编码gbk
response.getOutputStream().write("登陆成功!".getBytes(ENCODING));
} else {
response.getOutputStream().write("登陆失败!".getBytes(ENCODING));
}
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("这里是doPost");
doGet(request, response);
}


}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
智慧校园的建设目标是通过数据整合、全面共享,实现校园内教学、科研、管理、服务流程的数字化、信息化、智能化和多媒体化,以提高资源利用率和管理效率,确保校园安全。 智慧校园的建设思路包括构建统一支撑平台、建立完善管理体系、大数据辅助决策和建设校园智慧环境。通过云架构的数据中心与智慧的学习、办公环境,实现日常教学活动、资源建设情况、学业水平情况的全面统计和分析,为决策提供辅助。此外,智慧校园还涵盖了多媒体教学、智慧录播、电子图书馆、VR教室等多种教学模式,以及校园网络、智慧班牌、校园广播等教务管理功能,旨在提升教学品质和管理水平。 智慧校园的详细方案设计进一步细化了教学、教务、安防和运维等多个方面的应用。例如,在智慧教学领域,通过多媒体教学、智慧录播、电子图书馆等技术,实现教学资源的共享和教学模式的创新。在智慧教务方面,校园网络、考场监控、智慧班牌等系统为校园管理提供了便捷和高效。智慧安防系统包括视频监控、一键报警、阳光厨房等,确保校园安全。智慧运维则通过综合管理平台、设备管理、能效管理和资产管理,实现校园设施的智能化管理。 智慧校园的优势和价值体现在个性化互动的智慧教学、协同高效的校园管理、无处不在的校园学习、全面感知的校园环境和轻松便捷的校园生活等方面。通过智慧校园的建设,可以促进教育资源的均衡化,提高教育质量和管理效率,同时保障校园安全和提升师生的学习体验。 总之,智慧校园解决方案通过整合现代信息技术,如云计算、大数据、物联网和人工智能,为教育行业带来了革命性的变革。它不仅提高了教育的质量和效率,还为师生创造了一个更加安全、便捷和富有智慧的学习与生活环境。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值