学习笔记之网络访问基础

来源:互联网 发布:汇川plc编程手册pdf 编辑:程序博客网 时间:2024/06/08 10:18
/** * 点击按钮 * 利用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
原创粉丝点击