HTTP协议之Get请求

配置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();
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值