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

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);
					//返回码==200
					if(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();
                }


            

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值