准备条件,
编写一个web项目。编写一个servlet,若用户名为lisi,密码为123,则返回“登录成功”,否则”登录失败”。项目名为serveritheima28。代码如下:
package com.itheima28.servlet;
import java.io.ioexception;
import java.io.printwriter;
import javax.servlet.servletexception;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
public class loginservlet extends httpservlet {
/**
* the doget method of the servlet. <br>
*
* this method is called when a form has its tag value method equals to get.
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws servletexception if an error occurred
* @throws ioexception if an error occurred
*/
public void doget(httpservletrequest request, httpservletresponse response)
throws servletexception, ioexception {
string username = request.getparameter("username"); // 采用的编码是: iso-8859-1
string password = request.getparameter("password");
// 采用iso8859-1的编码对姓名进行逆转, 转换成字节数组, 再使用utf-8编码对数据进行转换, 字符串
username = new string(username.getbytes("iso8859-1"), "utf-8");
password = new string(password.getbytes("iso8859-1"), "utf-8");
system.out.println("姓名: " + username);
system.out.println("密码: " + password);
if("lisi".equals(username) && "123".equals(password)) {
/*
* getbytes 默认情况下, 使用的iso8859-1的编码, 但如果发现码表中没有当前字符,
* 会使用当前系统下的默认编码: gbk
*/
response.getoutputstream().write("登录成功".getbytes("utf-8"));
} else {
response.getoutputstream().write("登录失败".getbytes("utf-8"));
}
}
* the dopost method of the servlet. <br>
* this method is called when a form has its tag value method equals to post.
public void dopost(httpservletrequest request, httpservletresponse response)
system.out.println("dopost");
doget(request, response);
}
使用github上的android-async-http-master框架:
2 编写android应用,应用截图如下:
代码结构如下:
清单文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.itheim28.submitdata"
android:versioncode="1"
android:versionname="1.0" >
<uses-sdk
android:minsdkversion="8"
android:targetsdkversion="19" />
<uses-permission android:name="android.permission.internet"/>
<application
android:allowbackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/apptheme" >
<activity
android:name="com.itheim28.submitdata.mainactivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.main" />
<category android:name="android.intent.category.launcher" />
</intent-filter>
</activity>
</application>
</manifest>
3 编写布局文件activity_main.xml
<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=".mainactivity" >
<edittext
android:id="@+id/et_username"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="请输入姓名" />
android:id="@+id/et_password"
android:hint="请输入密码" />
<button
android:layout_width="wrap_content"
android:onclick="doget"
android:text="get方式提交" />
android:onclick="dopost"
android:text="post方式提交" />
android:onclick="dohttpclientofget"
android:text="使用httpclient方式提交get请求" />
android:onclick="dohttpclientofpost"
android:text="使用httpclient方式提交post请求" />
</linearlayout>
4 netutils的内容如下:
package com.itheim28.submitdata.utils;
import java.io.bytearrayoutputstream;
import java.io.inputstream;
import java.io.outputstream;
import java.net.httpurlconnection;
import java.net.url;
import java.net.urlencoder;
import android.util.log;
public class netutils {
private static final string tag = "netutils";
* 使用post的方式登录
* @param username
* @param password
* @return
public static string loginofpost(string username, string password) {
httpurlconnection conn = null;
try {
url url = new url(
"http://114.215.142.191:8080/serveritheima28/servlet/loginservlet");
conn = (httpurlconnection) url.openconnection();
conn.setrequestmethod("post");
conn.setconnecttimeout(10000); // 连接的超时时间
conn.setreadtimeout(5000); // 读数据的超时时间
conn.setdooutput(true); // 必须设置此方法, 允许输出
// 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;
* 使用get的方式登录
* @return 登录的状态
public static string loginofget(string username, string password) {
string data = "username=" + urlencoder.encode(username)
+ "&password=" + urlencoder.encode(password);
"http://114.215.142.191:8080/serveritheima28/servlet/loginservlet?"
+ data);
conn.setrequestmethod("get"); // get或者post必须得全大写
conn.disconnect(); // 关闭连接
* 根据流返回一个字符串信息
* @param is
* @throws ioexception
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();
string html = baos.tostring(); // 把流中的数据转换成字符串, 采用的编码是: utf-8
// string html = new string(baos.tobytearray(), "gbk");
baos.close();
return html;
5 netutils2代码如下:
import java.util.arraylist;
import java.util.list;
import org.apache.http.httpresponse;
import org.apache.http.namevaluepair;
import org.apache.http.client.httpclient;
import org.apache.http.client.entity.urlencodedformentity;
import org.apache.http.client.methods.httpget;
import org.apache.http.client.methods.httppost;
import org.apache.http.impl.client.defaulthttpclient;
import org.apache.http.message.basicnamevaluepair;
public class netutils2 {
httpclient client = null;
// 定义一个客户端
client = new defaulthttpclient();
// 定义post方法
httppost post = new httppost(
// 定义post请求的参数
list<namevaluepair> parameters = new arraylist<namevaluepair>();
parameters.add(new basicnamevaluepair("username", username));
parameters.add(new basicnamevaluepair("password", password));
// 把post请求的参数包装了一层.
// 不写编码名称服务器收数据时乱码. 需要指定字符集为utf-8
urlencodedformentity entity = new urlencodedformentity(parameters,
"utf-8");
// 设置参数.
post.setentity(entity);
// 设置请求头消息
// post.addheader("content-length", "20");
// 使用客户端执行post方法
httpresponse response = client.execute(post); // 开始执行post请求,
// 会返回给我们一个httpresponse对象
// 使用响应对象, 获得状态码, 处理内容
int statuscode = response.getstatusline().getstatuscode(); // 获得状态码
if (statuscode == 200) {
// 使用响应对象获得实体, 获得输入流
inputstream is = response.getentity().getcontent();
string text = getstringfrominputstream(is);
return text;
log.i(tag, "请求失败: " + statuscode);
if (client != null) {
client.getconnectionmanager().shutdown(); // 关闭连接和释放资源
// 定义一个get请求方法
httpget get = new httpget(
"http://114.215.142.191:8080/serveritheima28/servlet/loginservlet?" + data);
// response 服务器相应对象, 其中包含了状态信息和服务器返回的数据
// 开始执行get方法, 请求网络
httpresponse response = client.execute(get);
// 获得响应码
int statuscode = response.getstatusline().getstatuscode();
return text;
client.getconnectionmanager().shutdown(); // 关闭连接, 和释放资源
6 mainactivity代码如下:
package com.itheim28.submitdata;
import android.app.activity;
import android.os.bundle;
import android.text.textutils;
import android.view.view;
import android.widget.edittext;
import android.widget.toast;
import com.itheim28.submitdata.utils.netutils;
import com.itheim28.submitdata.utils.netutils2;
public class mainactivity extends activity {
private static final string tag = "mainactivity";
private edittext etusername;
private edittext etpassword;
@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);
* 使用httpclient方式提交get请求
* @param v
public void dohttpclientofget(view v) {
log.i(tag, "dohttpclientofget");
final string username = etusername.gettext().tostring();
final string password = etpassword.gettext().tostring();
new thread(new runnable() {
@override
public void run() {
// 请求网络
final string state = netutils2.loginofget(username, password);
// 执行任务在主线程中
runonuithread(new runnable() {
@override
public void run() {
// 就是在主线程中操作
toast.maketext(mainactivity.this, state, 0).show();
}
});
}).start();
* 使用httpclient方式提交post请求
public void dohttpclientofpost(view v) {
log.i(tag, "dohttpclientofpost");
final string state = netutils2.loginofpost(username, password);
@override
public void doget(view v) {
// 使用get方式抓去数据
final string state = netutils.loginofget(username, password);
public void dopost(view v) {
final string state = netutils.loginofpost(username, password);
7 mainactivity2 的代码如下:
import org.apache.http.header;
import com.loopj.android.http.asynchttpclient;
import com.loopj.android.http.asynchttpresponsehandler;
import com.loopj.android.http.requestparams;
public class mainactivity2 extends activity {
protected static final string tag = "mainactivity2";
private edittext etusername;
private edittext etpassword;
@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);
}
public void doget(view v) {
final string username = etusername.gettext().tostring();
final string password = etpassword.gettext().tostring();
asynchttpclient client = new asynchttpclient();
string data = "username=" + urlencoder.encode(username) + "&password="
+ urlencoder.encode(password);
client.get("http://114.215.142.191:8080/serveritheima28/servlet/loginservlet?"
+ data, new myresponsehandler());
public void dopost(view v) {
requestparams params = new requestparams();
params.put("username", username);
params.put("password", password);
client.post(
"http://114.215.142.191:8080/serveritheima28/servlet/loginservlet",
params, new myresponsehandler());
class myresponsehandler extends asynchttpresponsehandler {
@override
public void onsuccess(int statuscode, header[] headers,
byte[] responsebody) {
// log.i(tag, "statuscode: " + statuscode);
toast.maketext(
mainactivity2.this,
"成功: statuscode: " + statuscode + ", body: "
+ new string(responsebody), 0).show();
}
public void onfailure(int statuscode, header[] headers,
byte[] responsebody, throwable error) {
toast.maketext(mainactivity2.this, "失败: statuscode: " + statuscode,
0).show();