学习笔记之网络访问基础

/**
	 * 点击按钮
	 * 利用HttpClient以GET方式获取服务器上的图片
	 * 
	 * @param v
	 */
	public void getbyhc(View v){
		//1)所有网络访问代码都要写在工作线程中
		new Thread(){
			public void run() {
				try {
					//2)创建HttpClient对象
					HttpClient client = new DefaultHttpClient();
					//3)声明网络访问的方式GET
					//HttpGet get = new HttpGet("http://172.60.50.82:8080/ems/getCode.do");
					HttpGet get = new HttpGet("http://172.60.50.82:8080/ems/login.html");
					//4)发起网络访问
					//5)获得服务器响应
					HttpResponse resp = client.execute(get);
					//6)解析服务器返回的具体内容
					HttpEntity entity = resp.getEntity();
					InputStream is = entity.getContent();
					//Bitmap bitmap = BitmapFactory.decodeStream(is);
					
					BufferedReader br = new BufferedReader(new InputStreamReader(is));
					String line = null;
					StringBuilder sb = new StringBuilder();
					while((line=br.readLine())!=null){
						sb.append(line);
					}
					//is.close();
					br.close();
					//7)通过Message将结果从工作线程提交到主线程
					//Message.obtain(handler,101,bitmap).sendToTarget();
					Message.obtain(handler,102,sb.toString()).sendToTarget();
				} catch (Exception e) {
					e.printStackTrace();
				}
			};
		}.start();
	}


public void getbyuc(View v){
		new Thread(){
			public void run() {
				try {
					URL url = new URL("http://172.60.50.82:8080/ems/getCode.do");
					HttpURLConnection connection = (HttpURLConnection) url.openConnection();
					connection.setRequestMethod("GET");//设定访问方式
					connection.setDoInput(true);//可以接收服务器给我返回内容
					connection.connect();//建立连接
					InputStream is = connection.getInputStream();
					Bitmap bitmap = BitmapFactory.decodeStream(is);
					is.close();
					Message.obtain(handler, 101, bitmap).sendToTarget();
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			};
		}.start();
	}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值