1:post请求是键值对的形式获得数据,但是整体和get请求相同,首先还是创建一个Utils类,里面存放post 的静态解析方法,代码如下:
public static String postUrlConnect(String urlPath, Map<String,Object> map){ StringBuffer sbRequest =new StringBuffer(); if(map!=null&&map.size()>0){ for (String key:map.keySet()){ sbRequest.append(key+"="+map.get(key)+"&"); } } String request = sbRequest.substring(0,sbRequest.length()-1); try { //创建URL URL url = new URL(urlPath); //由URL的openConnection方法得到一个HttpURLConnection(需要强转) HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); //设置post提交 httpURLConnection.setRequestMethod("POST"); //设置超时时间 httpURLConnection.setConnectTimeout(30000); httpURLConnection.setReadTimeout(30000); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); //把请求正文通过OutputStream发出去 OutputStream os =httpURLConnection.getOutputStream(); os.write(request.getBytes()); os.flush(); //判断响应码 200 代表成功 if(httpURLConnection.getResponseCode()==200){ //由HttpURLConnection拿到输入流 InputStream in=httpURLConnection.getInputStream(); StringBuffer sb=new StringBuffer(); //根据输入流做一些IO操作 byte [] buff =new byte[1024]; int len=-1; while((len=in.read(buff))!=-1){ sb.append(new String(buff,0,len,"utf-8")); } in.close(); os.close(); httpURLConnection.disconnect(); return sb.toString(); }else{ return null; } }catch (Exception e){ Log.e("post","code:"+e.getMessage()); return null; } }
2:post请求的代码和get的基本相同,只是多添加了一个Map集合用来存放参数,定义好的post请求方法有两个参数,一个是字符串,存放网络地址路径,一个Map请求,存放请求参数,所以传入参数的时候也是如此,代码如下:
new Thread(){ @Override public void run() { super.run(); //http://m.yunifang.com/yunifang/mobile/goods/getall?random=39986&encode=2092d7eb33e8ea0a7a2113f2d9886c90&category_id=17 //第一个参数,链接路径,最后的?忘了用不用写了,自己试试吧 String a="http://m.yunifang.com/yunifang/mobile/goods/getall?"; //定义map集合 Map<String,Object> map=new Hashtable<String, Object>(); //存入参数 map.put("random","39986"); map.put("encode","2092d7eb33e8ea0a7a2113f2d9886c90"); map.put("category_id","17"); //调用post解析方法,得到解析后的Gson字符串 String utils = Utils.postUrlConnect(a,map); Message msg=new Message(); msg.obj=utils; msg.what=1; //传入handle handler.sendMessage(msg); } }.start();
3:handle方法里面的就和get请求一样了,代码如下:
Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); //switch是为了放止多个线程出浑谣,如果只是一个的话可以不写 switch (msg.what) { case 1: //得到请求获得的Gson串 String pose=msg.obj.toString(); Gson gson = new Gson(); //解析gson串,存入对象Bean中 Bean bean = gson.fromJson(pose, Bean.class); //将bean类里需要的数据存入集合,getData在bean类中就是一个集合 //private List<DataBean> data; arr=bean.getData(); //打印 Log.e("str",arr.size()+""); //适配器 adapter=new Myadapter(MainActivity.this,arr); listview.setAdapter(adapter); //刷新适配器 adapter.notifyDataSetChanged(); break; } } };