android 实现服务器连接获取数据和传递数据(1)

来源:互联网 发布:搞怪视频软件 编辑:程序博客网 时间:2024/06/04 00:38

1:apache公司: httpclient

 

a: 创建HttpGet或者HttpPost对象,将要请求的URL对象构造方法传入HttpGet、HttpPost对象

b:通过HttpClent接口的实现类DefaultClent.的excute(HttpUriRequest request)而我们已经知道HttpGet和HttpPost类都实现了HttpUriRequest接口,所以这里面,我们可以将第1步创建好的HttpGet或者HttpPost对象传入进来。来得到HttpResponse对象

c:通过HttpResponse取到返回的一些信息,再做提取

     使用HttpGet调用有一个缺点就是,请求的参数作为URL一部分来传递,以这种方式传递的时候,URL的长度应该在2048个字符之内。如果超出这个这范围,就要使用到HttpPost调用。

     在数据请求中有UrlEncodedUtils 类 可以解析和格式参数,以 键=值 传递

     实例:httpget.
String urlPath ="http://www.baidu.com/";HttpClient client=new DefaultHttpClient();try {List<NameValuePair> value=new ArrayList<NameValuePair>();//需要传递的参数value.add(new BasicNameValuePair("id", "98685"));value.add(new BasicNameValuePair("name", "libai"));String params=URLEncodedUtils.format(value, "UTF-8");urlPath+="?"+params;HttpGet get=new HttpGet(urlPath);HttpResponse execute = client.execute(get);//返回码==200if(execute.getStatusLine().getStatusCode()==200){HttpEntity entity = execute.getEntity();if(entity!=null){//注意这里entity只能被消耗一次 意思是对其处理只能一次不然会报错//下面是两次处理 放在一起会报错 Content has been consumed。//按照编码方式将返回数据转换成string类型String string = EntityUtils.toString(entity, "Utf-8");//得到输入流对象 InputStream instream=entity.getContent();//下面进行数据解析 json、xml等}}} catch (ClientProtocolException e1) {e1.printStackTrace();} catch (IOException e1) {e1.printStackTrace();}
httppost:

  HttpClient client=new DefaultHttpClient();
                HttpPost post=new HttpPost(urlPath);
                try {
                    List<NameValuePair> value=new ArrayList<NameValuePair>();
                    //需要传递的参数
                    value.add(new BasicNameValuePair("id", "98685"));
                    //实例化 即将键值对组成 建=值&建=值 方式
                    UrlEncodedFormEntity EncodedFormEntity = new UrlEncodedFormEntity(value);
                    post.setEntity(EncodedFormEntity);
                    
                    HttpResponse response = client.execute(post);
                    //下面和get 一样
                } catch (ClientProtocolException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }


            

0 0
原创粉丝点击