登陆验证实例——提交数据到服务器
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方法。
接下来我们将介绍通过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。
所以当客户端提交数据会将会从服务端得到一个字符串,我们将设置以下方法从返回的流数据从读取并转化为字符串。
下面我们已登陆验证为例,提交网络的方式主要有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; }
相关文章推荐
- Silverlight实例教程 - Validation用户提交数据验证捕获
- Silverlight实例教程 - Validation用户提交数据验证捕获(转载)
- Sql2012如何将远程服务器数据库及表、表结构、表数据导入本地数据库 自定义日志记录功能,按日记录,很方便 C#常量和字段以及各种方法的语法总结 类型,对象,线程栈,托管堆在运行时的关系,以及clr如何调用静态方法,实例方法,和虚方法 asp.net webapi 自定义身份验证
- Silverlight实例教程 - Validation用户提交数据验证捕获
- 表单提交数据的方式 怎么在服务器获取 服务器控件 html服务器控件 提交服务器之前的验证 前台网页编写c#代码
- HttpClient下载图片和向服务器提交数据实例
- python+httplib实现HTTP POST提交数据,使用Basic Authentication(基本验证)做登陆验证
- 登陆验证姓名密码,自动登录 ,get获取服务器数据,显示表格形式到界面
- Android实例] android获取web服务器端session并验证登陆
- Silverlight实例教程 - Validation用户提交数据验证捕获
- 以申购单为实例,讲解Jquery动态删减行,新增行添加鼠标事件,子窗口与父窗口传值,自动计算金额,及输入值的验证,前台数据批量提交到后台action
- windows phone 7 通过Post提交URL到服务器,从服务器获取数据(比如登陆时候使用)
- android利用get提交数据到服务器进行验证
- vue组件表单数据回显验证及提交的实例代码
- HttpClient下载图片和向服务器提交数据实例
- android,get发送数据到服务器,服务器验证登陆
- 微信小程序服务器请求和上传数据,上传图片并展示,提交表单完整实例代码附效果图
- 采用get方式提交数据到服务器实例
- windows phone 7 通过Post提交URL到服务器,从服务器获取数据(比如登陆时候使用)
- Silverlight实例教程 - Validation用户提交数据验证捕获