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

来源:互联网 发布:c语言心形图案 编辑:程序博客网 时间:2024/04/29 02:00

需求:写一个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
原创粉丝点击