注意点:
1、访问网络的工作不能在主线程(UI)中进行,如果耗时过程则会导致程序出错 ------(子线程中进行)
2、子线程不能更新UI -------(主线程中进行)
3、使用Handler配合子线程更新主线程时要注意内存泄露的问题,解决内存泄露的方法之一就是以弱引用的形式:
//弱引用,防止内存泄露
private static class MyHandler extends Handler {
private final WeakReference mActivity;
public MyHandler(MainActivity activity) {
mActivity = new WeakReference(activity);
}
@Override
public void handleMessage(Message msg) {
System.out.println(msg);
if (mActivity.get() == null) {
return;
}
mActivity.get().updateUIThread(msg);
}
}
//我们请求的数据
String data = "password="+ URLEncoder.encode(passwd,"UTF-8")+
"&username="+URLEncoder.encode(username,"UTF-8");
5、使用模拟器进行测试时,URL中的IP地址不是127.0.0.1,而是10.0.2.2
private static String LOGIN_URL = "http://10.0.2.2:8080/webtest/loginaction";
实例:在Android客户端中输入用户名和密码之后,将其提交至服务器,服务器进行判断用户名和密码是否正确,如果正确则返回success,失败则返回fail
配置服务器
在搭建好tomcat服务器之后,在eclipse中创建servlet文件
LoginAction.java(服务器)
package Login;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/**
* Servlet implementation class LoginAction
*/
@WebServlet("/LoginAction")
public class LoginAction extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginAction() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
//设置客户端的解码方式为utf-8
response.setContentType("text/html;charset=utf-8");
//
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
String result = "";
String name = request.getParameter("username");
String pwd = request.getParameter("password");
//System.out.println("name="+name);
//System.out.println("password="+pwd);
if (name.equals("admin")&&pwd.equals("123")) {
result = "success";
}
else{
result = "fail";
}
out.write(result);
out.flush();
out.close();
System.out.println(result);
}
}
在eclipse中中配置web.xm文件,该文件一般在WebContent ---> WEB-INF的文件夹下
在web.xml文件中添加如下代码:
LoginAction
Login.LoginAction
LoginAction
/loginaction
Android客户端
MainActivity.java
package com.example.administrator.httpconnectlogin;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.lang.ref.WeakReference;
public class MainActivity extends AppCompatActivity {
private Button button;
private EditText edit1,edit2;
private MyHandler myhandler = new MyHandler(this);
public static final String TAG="MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InitView();
}
//弱引用,防止内存泄露
private static class MyHandler extends Handler {
private final WeakReference mActivity;
public MyHandler(MainActivity activity) {
mActivity = new WeakReference(activity);
}
@Override
public void handleMessage(Message msg) {
System.out.println(msg);
if (mActivity.get() == null) {
return;
}
mActivity.get().updateUIThread(msg);
}
}
//配合子线程更新UI线程
private void updateUIThread(Message msg){
Bundle bundle = new Bundle();
bundle = msg.getData();
String result = bundle.getString("result");
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
void InitView(){
button = (Button) findViewById(R.id.btn);
edit1 = (EditText) findViewById(R.id.editText1);
edit2 = (EditText) findViewById(R.id.editText2);
// Toast.makeText(MainActivity.this, "str111", Toast.LENGTH_SHORT).show();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (edit1.toString().isEmpty()||edit2.toString().isEmpty()) {
Toast.makeText(MainActivity.this, "学号或密码不能为空", Toast.LENGTH_SHORT).show();
}
else{
//开启访问数据库线程
new Thread(new Runnable() {
@Override
public void run() {
String str = HttpLogin.LoginByPost(edit1.getText().toString(),edit2.getText().toString());
Bundle bundle = new Bundle();
bundle.putString("result",str);
Message msg = new Message();
msg.setData(bundle);
myhandler.sendMessage(msg);
}
}).start();
}
}
});
}
}
HttpLogin.java
package com.example.administrator.httpconnectlogin;
import android.util.Log;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Administrator on 2016/10/5.
*/
public class HttpLogin {
private static String LOGIN_URL = "http://10.0.2.2:8080/webtest/loginaction";
public static String LoginByPost(String username,String passwd){
Log.d(MainActivity.TAG,"启动登录线程");
String msg = "";
try {
//初始化URL
URL url = new URL(LOGIN_URL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Log.d(MainActivity.TAG,"11111");
//设置请求方式
conn.setRequestMethod("POST");
//设置超时信息
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
//设置允许输入
conn.setDoInput(true);
//设置允许输出
conn.setDoOutput(true);
//post方式不能设置缓存,需手动设置为false
conn.setUseCaches(false);
//我们请求的数据
String data = "password="+ URLEncoder.encode(passwd,"UTF-8")+
"&username="+URLEncoder.encode(username,"UTF-8");
//獲取輸出流
OutputStream out = conn.getOutputStream();
out.write(data.getBytes());
out.flush();
out.close();
conn.connect();
if (conn.getResponseCode() == 200) {
// 获取响应的输入流对象
InputStream is = conn.getInputStream();
// 创建字节输出流对象
ByteArrayOutputStream message = new ByteArrayOutputStream();
// 定义读取的长度
int len = 0;
// 定义缓冲区
byte buffer[] = new byte[1024];
// 按照缓冲区的大小,循环读取
while ((len = is.read(buffer)) != -1) {
// 根据读取的长度写入到os对象中
message.write(buffer, 0, len);
}
// 释放资源
is.close();
message.close();
// 返回字符串
msg = new String(message.toByteArray());
return msg;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.d(MainActivity.TAG,"exit");
return msg;
}
}