本文共 2952 字,大约阅读时间需要 9 分钟。
我们做android开发免不了要向后台服务器获得数据,一般情况下,都是使用http协议进行获取。
1、什么是http协议:
简单来说,我们上网在浏览器地址栏输入地址相当于告诉浏览器(客户端)我要浏览哪个网页,浏览器根据你输入的地址里获取你要访问的具体服务器及内容并显示出来。Http协议就是一个规范,客户端和服务器端都认同的规范,客户端根据这个规范把要请求的数据按照一定格式组织好发送出去。而服务器在客户端的请求后,根据请求里的要求把相应的内容返回给客户端。做个比喻,你网上买车票,你肯定要填写相应的出发地,到达地,出发时间等信息,然后卖票的系统根据你填写的信息给你相应的车票。http协议就像你填信息的那个单子,那个单子你(客户端)会填写,卖票的系统(服务器)也读得懂。这个单子就相当于你跟卖票系统之间的规范。
2、如何使用
我们这里主讲向服务器请求数据的get方法和向服务器提交数据的post方法。现在看具体代码
get方法会把请求的一些参数放在url里如 ,该url后的 就是信息参数多个参数之间用&连接如?wd=TChengZ&id=1。
public void get(){ BufferedReader in = null; try{ HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet("http://www.baidu.com/s?wd=TChengZ"); HttpResponse response = client.execute(request); HttpEntity httpEntity = response.getEntity(); in = new BufferedReader(new InputStreamReader(httpEntity.getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while((line = in.readLine()) != null){ sb.append(line + NL); } in.close(); String page = sb.toString(); Log.i(TAG, page); }catch(Exception e){ Log.e(TAG,e.toString()) }finally{ if(in != null){ try{ in.close(); }catch(IOException ioe){ Log.e(TAG, ioe.toString()); } } } }post方法则会将信息参数放在内容中:
public void post(){ BufferedReader in = null; try{ NameValuePair nameValuePair = new BasicNameValuePair("wd", "TChengZ"); ListpostParams = new List (); postParams.add(nameValuePair); //设置信息,不止一个信息就多几个NameValuePair并放到该list HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://www.baidu.com/s"); HttpEntity entity = new UrlEncodeFormEntity(postParams); post.setEntity(entity);//将信息放到post数据内容里 HttpResponse response = client.execute(request); //发送post数据并得到返回数据 in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while((line = in.readLine()) != null){ sb.append(line + NL); } in.close(); String result = sb.toString(); Log.i(TAG, result ); }catch(Exception e){ Log.e(TAG,e.toString()) }finally{ if(in != null){ try{ in.close(); }catch(IOException ioe){ Log.e(TAG, ioe.toString()); } } }
转载地址:http://bfsub.baihongyu.com/