Android网络请求数据

1.main.xml: 
    listView
2item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
         android:layout_width="150dp"
         android:layout_height="wrap_content"
         android:id="@+id/title"
         android:text="13547907127"
        />
    <TextView
         android:layout_width="50dp"
         android:layout_height="wrap_content"
         android:id="@+id/timeLength"
         android:text="100"
        />
</LinearLayout>

2.servlet
public class ListServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/xml;charset=utf-8");
        System.out.println("接收到请求....");
        Writer out=response.getWriter();
        List<News> list=new ArrayList<News>();
        list.add(new News(35,"喜洋洋与灰太狼",90));
        list.add(new News(12,"老张与灰太狼",20));
        list.add(new News(56,"刘德华与灰太狼",30));
        list.add(new News(36,"张学友与灰太狼",10));
        list.add(new News(32,"郭富城与灰太狼",40));
        list.add(new News(31,"黎明与灰太狼",50));
        
        Map<String,Class<?>> alias=new HashMap<String,Class<?>>();
        alias.put("videonews",List.class);
        alias.put("news",News.class);
        String xml=XStreamUtil.getInstance().obj2xml(list,alias);
        System.out.println(xml);
        out.write(xml);
    }

}

4.android-service
public class VideoNewsService {

    //从服务端获取XML数据
    public List<News> getLastNews() throws Exception{
        String path="http://192.168.0.112:8080/Test1/list.do";
        URL url=new URL(path);
        HttpURLConnection con=(HttpURLConnection) url.openConnection();
        con.setReadTimeout(5000);
        con.setRequestMethod("GET");
        if(con.getResponseCode()==200){
            InputStream in=con.getInputStream();
            return parseXml(in);
        }
        return null;
    }
      
    //XML数据解析为对象数据
    private List<News> parseXml(InputStream in) throws Exception{
        XmlPullParser pullParser=Xml.newPullParser();
        pullParser.setInput(in, "UTF-8");
        int event=pullParser.getEventType();
        List<News> news=null;
        News person=null;
        while(event!=XmlPullParser.END_DOCUMENT){
            switch (event){
            case XmlPullParser.START_DOCUMENT:
                news=new ArrayList<News>();
                break;
            case XmlPullParser.START_TAG:
                if("news".equals(pullParser.getName())){
                    person=new News();
                }
                if("id".equals(pullParser.getName())){
                    String id=pullParser.nextText();
                    person.setId(Integer.valueOf(id));
                }
                if("title".equals(pullParser.getName())){
                    String name=pullParser.nextText();
                    person.setTitle(name);
                }
                if("timeLength".equals(pullParser.getName())){
                    int age=new Integer(pullParser.nextText());
                    person.setTimeLength(Integer.valueOf(age));
                }
                break;
            case XmlPullParser.END_TAG:
                if("news".equals(pullParser.getName())){
                    news.add(person);
                    person=null;
                }
                break;
            }
        
            event=pullParser.next();
        }
        return news;
    }
}
5.mainActity.java
private void show2(){
        try {
            VideoNewsService dao=new VideoNewsService();
            List<News> datas=dao.getLastNews(true);
            List<HashMap<String,Object>> data=new ArrayList<HashMap<String,Object>>();
            for(News news:datas){
                HashMap<String,Object> item=new HashMap<String,Object>();
                item.put("id",news.getId());
                item.put("title",news.getTitle());
                item.put("timeLength",news.getTimeLength());
                data.add(item);
            }
            SimpleAdapter adapter=new SimpleAdapter(getApplicationContext(),
                    data,R.layout.item,
                    new String[]{"title","timeLength"},
                    new int[]{R.id.title,R.id.timeLength});
            ListView listView=(ListView)findViewById(R.id.listView);
            listView.setAdapter(adapter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

6.model
public class News {

    private int id;
    private String title;
    private Integer timeLength;
}
//////////////json
1.servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/xml;charset=utf-8");
        System.out.println("接收到请求....");
        Writer out=response.getWriter();
        List<News> list=new ArrayList<News>();
        list.add(new News(35,"喜洋洋与灰太狼",90));
        list.add(new News(12,"老张与灰太狼",20));
        list.add(new News(56,"刘德华与灰太狼",30));
        list.add(new News(36,"张学友与灰太狼",10));
        list.add(new News(32,"郭富城与灰太狼",40));
        list.add(new News(31,"黎明与灰太狼",50));
          
        StringBuffer sb=new StringBuffer("[");
        for(int i=0;i<list.size();i++){
            News news=list.get(i);
            sb.append("{'id':"+news.getId()+",");
            sb.append("'title':'"+news.getTitle()+"',");
            sb.append("'timeLength':"+news.getTimeLength()+"}");
            if(i!=list.size()-1) sb.append(",");
        }
        sb.append("]");
        String json=sb.toString();
        System.out.println(json);
        out.write(json);
    }

3.android-service
public List<News> getLastNews() throws Exception{
        String path="http://192.168.0.112:8080/Test1/list.do";
        URL url=new URL(path);
        HttpURLConnection con=(HttpURLConnection) url.openConnection();
        con.setReadTimeout(5000);
        con.setRequestMethod("GET");
        if(con.getResponseCode()==200){
            byte[] data=StreamTool.read(con.getInputStream());
            String result=new String(data);
            JSONArray array=new JSONArray(result);
            List<News> list=new ArrayList<News>();
            for(int i=0;i<array.length();i++){
                JSONObject obj=array.getJSONObject(i);
                News news=new News();
                news.setId(obj.getInt("id"));
                news.setTitle(obj.getString("title"));
                news.setTimeLength(obj.getInt("timeLength"));
                list.add(news);
            }
            return list;
        }
        return null;
    }


你可能感兴趣的:(Android网络请求数据)