您的位置:首页 > 理论基础 > 计算机网络

登陆验证实例——提交数据到服务器

2014-12-17 18:56 225 查看
一个Android手机软件如果能够连接网络,那么这个APP是活的,它将有更多的可能性,所以如何实现手机与网络通信时相当重要的。

下面我们已登陆验证为例,提交网络的方式主要有GET和POST两种方式,而建立连接又通常有两种方法,所以我们下面将实现四段向服务器提交数据的代码。

首先,我们先来实现页面布局。

<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.jinglion.submitdatanet.MainActivity" >

<EditText
android:id="@+id/et_username"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="请输入名字"/>
<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="doGET"
android:text="GET方式提交"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="doPOST"
android:text="POST方式提交"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="doHttpClientOfGET"
android:text="使用HttpClient方式提交GET请求"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="doHttpClientOfPOST"
android:text="使用HttpClient方式提交POST请求"/>
</LinearLayout>
由上面xml布局的代码来看,共有两个输入框和四个按钮,这四个按钮将实现四种请求方法。

一、通过HttpURLConnection提交GET请求

设置第一个按钮为通过HttpURLConnection提交GET请求,按钮对应的方法是doGET();

public void doGET(View v){
final String username = etusername.getText().toString();
final String password = etpassword.getText().toString();

new Thread(new Runnable() {

@Override
public void run() {
//使用GET方法抓取数据
final String state = NetUtils.LoginOfGet(username, password);
//在UI线程中执行以下代码,即在主线程中执行,也可使用handle传递消息在主线程中执行。
runOnUiThread(new Runnable() {

@Override
public void run() {
Toast.makeText(MainActivity.this, "登陆状态:" + state, Toast.LENGTH_SHORT).show();

}
});
}
}).start();

}真正实现提交数据的是LoginOfGet方法。
public static String LoginOfGet(String username, String password){
HttpURLConnection conn = null;
try {
String data = "username="+username +"&password="+password;
URL url = new URL("http://10.0.2.2:8080/jingliontext/servlet/LoginServlet?"+data);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
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 {
conn.disconnect();
}
return null;
}

二、通过HttpURLConnection提交POST请求
设置第一个按钮为通过HttpURLConnection提交POST请求,按钮对应的方法是doPOST();
public void doPOST(View v){
final String username = etusername.getText().toString();
final String password = etpassword.getText().toString();

new Thread(new Runnable() {

@Override
public void run() {
//使用POST方法抓取数据
final String state = NetUtils.LoginOfPost(username, password);
//在UI线程中执行以下代码,即在主线程中执行,也可使用handle传递消息在主线程中执行。
runOnUiThread(new Runnable() {

@Override
public void run() {
Toast.makeText(MainActivity.this, "登陆状态:" + state, Toast.LENGTH_SHORT).show();

}
});
}
}).start();
}真正实现提交数据的是LoginOfPost方法。
/**
* 使用POST的方式登录
* @param username
* @param password
* @return 登陆的状态
*/
public static String LoginOfPost(String username, String password){
HttpURLConnection conn = null;
try {
URL url = new URL("http://10.0.2.2:8080/jingliontext/servlet/LoginServlet");
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(10000);
conn.setReadTimeout(5000);
//需要向服务器写入的参数
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) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (conn!=null) {
conn.disconnect();
}
}
return null;
}


接下来我们将介绍通过httpclient方式提交数据,由于MainActivity处的方法均相同,此处便不再重复,只写提交数据段的代码。

三、通过HttpURLConnection提交GET请求

/**
* 使用GET的方式登录
* @param username
* @param password
* @return 登陆的状态
*/
public static String LoginOfGet(String username, String password){
//http://10.0.2.2:8080/jingliontext/servlet/LoginServlet
HttpClient client = null;
try {
//定义一个客户端
client = new DefaultHttpClient();

//定义一个GET请求方法
String data = "username="+username+"&password="+password;
HttpGet get = new HttpGet("http://10.0.2.2:8080/jingliontext/servlet/LoginServlet?"+data);
/*
* 开始执行get请求,请求网络,返回response服务器相应对象,其中包含了状态信息和所传输的数据
*/
HttpResponse response = client.execute(get);
//获得响应码
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
InputStream is = response.getEntity().getContent();
String text = getStringFromInputStream(is);
return text;
} else {
Log.i(TAG, "请求失败:statusCode="+statusCode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (client!=null) {
client.getConnectionManager().shutdown();
}
}
return null;
}

四、通过HttpURLConnection提交POST请求
/**
* 使用POST的方式登录
* @param username
* @param password
* @return 登陆的状态
*/
public static String LoginOfPost(String username, String password){
HttpClient client
4000
= null;
try {
//定义一个客户端
client = new DefaultHttpClient();

//使用POST方法
HttpPost post = new HttpPost("http://10.0.2.2:8080/jingliontext/servlet/LoginServlet");

//定义POST请求参数
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username", username));
parameters.add(new BasicNameValuePair("password", password));

//把POST请求包装了一层
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters);

//请求参数
post.setEntity(entity);

//使用客户端执行POST方法,返回给我们一个HttpResponse对象
HttpResponse response = client.execute(post);
//使用相应对象,获得状态码,处理内容
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
//使用响应对象获得实体,获得输入流
InputStream is = response.getEntity().getContent();
String text = getStringFromInputStream(is);
return text;
} else {
Log.i(TAG, "请求失败:statusCode="+statusCode);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (client!=null) {
client.getConnectionManager().shutdown();
}
}

return null;
}
由于服务器端的设置是客户端提交用户密码后,服务端将进行校验,若用户名和密码均正确,则返回字符串success,反之则返回failed。

所以当客户端提交数据会将会从服务端得到一个字符串,我们将设置以下方法从返回的流数据从读取并转化为字符串。

/**
* 根据流返回一个字符串信息
* @param is
* @return
* @throws IOException
*/
private static String getStringFromInputStream(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0 ;
while ((len=is.read(buffer))!=-1) {
baos.write(buffer, 0, len);
}
is.close();

String html = baos.toString();   //把流中的数据转换为字符串。    默认使用utf-8
baos.close();

return html;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 网络 编程
相关文章推荐