<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText
android:id="@+id/et1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="请输入用户名"
/>
<EditText
android:id="@+id/et2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="请输入密码"
/>
<Button
android:id="@+id/btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="登录"/>
</LinearLayout>
package com.example.getmenthod;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MyActivity extends Activity {
private EditText ed1;
private EditText ed2;
private Button btn;
private Handler handler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ed1 = (EditText) findViewById(R.id.et1);
ed2 = (EditText) findViewById(R.id.et2);
btn = (Button) findViewById(R.id.btn);
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
String resu = (String) msg.obj;
Toast.makeText(MyActivity.this,resu,Toast.LENGTH_SHORT).show();
}
};
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String username = ed1.getText().toString();
String password = ed2.getText().toString();
String path = "http://192.168.21.1:8080/ok/servlet/Login?username="+username+"&password="+password;
getMethod(path);
}
});
}
private void getMethod(final String path){
//线程里访问网络
Thread thread = new Thread(){
@Override
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
if(conn.getResponseCode()==200){
//获得输入流
InputStream in = conn.getInputStream();
String result = getDataFromIn(in);
//消息队列发送消息
Message message = handler.obtainMessage();
message.obj = result;
handler.sendMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
}
private static String getDataFromIn(InputStream in){
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int len = 0;
try {
while ((len = in.read(b))!=-1){
out.write(b,0,len);
}
} catch (IOException e) {
e.printStackTrace();
}
return new String(out.toByteArray());
}
}