配置Manifest的网络访问权限:
简单的布局文件
Activity代码:
public class MainActivity extends Activity{
Button bu;
EditText title,timelength;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);//加载布局文件
bu = (Button) findViewById(R.id.button);//找出按钮id
title = (EditText) findViewById(R.id.ed_1);
timelength = (EditText) findViewById(R.id.ed_2);
bu.setOnClickListener(new OnClickListener() {//监听按钮操作
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String url = "http://192.168.1.100:8080/web2/Myservlet";//与服务器建立连接(tomcat服务器)
new Service(url,title.getText().toString(),timelength.getText().toString()).start();
}
});
}
}
Service代码:
public class Service extends Thread {
String url;
String title;
String timelength;
//构造函数
public Service(String url, String title, String timelength) {
// TODO Auto-generated constructor stub
super();
this.url = url;
this.title = title;
this.timelength = timelength;
}
//doget方法
private void doGet(){
try {
url = url+"?title="+URLEncoder.encode(title, "UTF-8")+"&timelength="+timelength;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
URL httpurl = new URL(url);
try {
HttpURLConnection conn = (HttpURLConnection) httpurl.openConnection();
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
BufferedReader bur= new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer();
String line = null;
while((line = bur.readLine())!=null){
sb.append(line);
}
System.out.println("result="+sb.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
doGet();
}
}