MianActivity中:
public class MainActivity extends Activity {
private EditText et_username, et_password;
private Button bt_login;
String result = "";
private static final String URL = "http://192.168.4.134:18080/test/servlet/LoginServlet";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
bt_login.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 1) {
Toast.makeText(MainActivity.this, result,
Toast.LENGTH_SHORT).show();
}
}
};
/** 启动线程 */
new Thread() {
public void run() {
/** 请求网络 */
loginByGet(et_username.getText().toString(),
et_password.getText().toString());
/** 发送消息到handler */
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
}.start();
}
});
}
private void init() {
et_username = (EditText) findViewById(R.id.et_username);
et_password = (EditText) findViewById(R.id.et_password);
bt_login = (Button) findViewById(R.id.bt_login);
}
public void loginByGet(String username, String password) {
try {
// 1、设置请求的地址。通过URLEncoder.encode(String s,"UTF-8")将字符串转换为UTF-8编码
String strURL = URL + "?username="
+ URLEncoder.encode(username, "utf-8") + "&password="
+ URLEncoder.encode(password, "utf-8") + "";
// 2、根据地址创建URL对象(网络访问的url)
URL url = new URL(strURL);
// 3、url.openConnection()打开网络链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 4、获取响应的输入流对象
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer buffer = new StringBuffer();
String line = null;
// 5、读取服务器返回信息
while ((line = bufferedReader.readLine()) != null) {
buffer.append(line);
}
result = buffer.toString();
// 6、关闭流,关闭http连接
bufferedReader.close();
conn.connect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
activity_main.xml中:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="用户名" />
<EditText
android:id="@+id/et_username"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="密码" />
<EditText
android:id="@+id/et_password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/bt_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="登录" />
</LinearLayout>