1、创建Web项目:
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println("username:" + username + "\t" + "password:" + password);
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
PrintWriter out = resp.getWriter();
String msg = null;
if (username.trim().equals("") || username.trim().length() == 0) {
msg = "用户名不能为空!";
} else if (password.trim().equals("") || password.trim().length() == 0) {
msg = "密码不能为空!";
} else if (username.trim().equals("admin") && password.trim().equals("123")) {
msg = "登陆成功!";
} else {
msg = "用户名或密码错误!";
}
System.out.println(msg);
out.print(msg);
out.flush();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
在web.xml中添加Servlet
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<form action="LoginServlet" method="post">
用户名:<input type="text" name="username"/><br>
密码:<input type="text" name="password"/><br>
<input type="submit" value="提交"/>
</form>
</body>
</html>
创建Android项目:
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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<EditText
android:id="@+id/et_useruname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入用户名" >
</EditText>
<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码" >
</EditText>
<Button
android:id="@+id/btn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="登录" />
</LinearLayout>
MainActivity:
public class MainActivity extends Activity {
private EditText et_username, et_password;
private Button btn_login;
private String str = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_username = (EditText) findViewById(R.id.et_useruname);
et_password = (EditText) findViewById(R.id.et_password);
btn_login = (Button) findViewById(R.id.btn_login);
btn_login.setOnClickListener(onClickListener);
}
private OnClickListener onClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
String username = et_username.getText().toString();
String password = et_password.getText().toString();
final String urlStr = "http://192.168.1.102:8080/android_web_login/LoginServlet?"
+ "username=" + username + "&password=" + password;
// android4.0以后不能在主线程发起网络请求
new Thread() {
public void run() {
str = HttpUtils.doGet(urlStr);
// 在线程中执行UI操作
Looper.prepare();
showToast(str);
Looper.loop();
};
}.start();
}
};
private void showToast(String msg) {
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
网络连接工具类HttpUtils:
/**
* Get请求,获得返回数据
*
* @param urlStr
* @return
* @throws Exception
*/
public static String doGet(String urlStr)
{
URL url = null;
HttpURLConnection conn = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try
{
url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
conn.setRequestMethod("GET");
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
if (conn.getResponseCode() == 200)
{
is = conn.getInputStream();
baos = new ByteArrayOutputStream();
int len = -1;
byte[] buf = new byte[128];
while ((len = is.read(buf)) != -1)
{
baos.write(buf, 0, len);
}
baos.flush();
return baos.toString();
} else
{
throw new RuntimeException(" responseCode is not 200 ... ");
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
try
{
if (is != null)
is.close();
} catch (IOException e)
{
}
try
{
if (baos != null)
baos.close();
} catch (IOException e)
{
}
conn.disconnect();
}
return null ;
}
最后记得添加访问网络权限:
<uses-permission android:name="android.permission.INTERNET" />
执行效果截图: