Android网络通信(一)

服务器端:

Javabean

public class News {
 
    private int id;
    private String name;
    private Integer timeLength;
 
    public News() {
    }
 
    public News(int id, String name, int timeLength) {
       this.id = id;
       this.name = name;
       this.timeLength = timeLength;
    }
 
    public int getId() {
       return id;
    }
 
    public void setId(int id) {
       this.id = id;
    }
 
    public String getName() {
       return name;
    }
 
    public void setName(String name){
       this.name = name;
    }
 
    public IntegergetTimeLength() {
       return timeLength;
    }
 
    public voidsetTimeLength(Integer timeLength) {
       this.timeLength = timeLength;
    }
 
}

Filter字符编码过滤器

public class CharacterEncodingFilter implements Filter {
    public voiddoFilter(ServletRequest request, ServletResponse response,
           FilterChainchain) throws IOException, ServletException { 
      
       HttpServletRequestreq = (HttpServletRequest) request;
       HttpServletResponseres = (HttpServletResponse) response;
      
       req.setCharacterEncoding("UTF-8");
       res.setCharacterEncoding("UTF-8");
      
       chain.doFilter(new WarpEncodingRequest(req),response);
    }
 
    public void destroy() {}
    public void init(FilterConfigarg0) throws ServletException {}
 
}

class WarpEncodingRequest extendsHttpServletRequestWrapper{
 
    privateHttpServletRequest  request =(HttpServletRequest) this.getRequest() ;
   
    publicWarpEncodingRequest(HttpServletRequest request) {
       super(request);
       // TODO Auto-generated constructor stub
    }
 
    @Override
    public StringgetParameter(String name) {
      
       try {
       Stringval = request.getParameter(name);
       if(val == null){
           return null;
       }
      
       if(request.getMethod().equalsIgnoreCase("POST")){
           return val;
       }     
      
           return newString(val.getBytes("ISO8859-1"),"UTF-8");
          
       }catch (Exception e) {
           throw newRuntimeException(e);
       }
    }
}

业务类

public class VedioServiceImpl implements VedioService {
   
    public List<News>getlastNews(){
       //简单地进行数据获取
       List<News>ns = new ArrayList<News>();
       ns.add(new News(1,"康斯坦丁",50));
       ns.add(new News(2,"少年厨艺大师",40));
       ns.add(new News(3,"NBA",20));
       ns.add(new News(4,"康斯",20));
        ns.add(new News(5,"坦丁",20));
      
       return ns;
    }
}

Servlet

public class ListNewsServlet extends HttpServlet {
   
    private VedioService service = new VedioServiceImpl();
   
    //servlet转发到jsp中生成json数据或xml数据
    public voiddoGet(HttpServletRequest request, HttpServletResponse response)
           throws ServletException,IOException {    
       List<News>ns = service.getlastNews();   
       Stringformat = request.getParameter("format");
       if("json".equalsIgnoreCase(format)){      //判断是否请求时Json格式
           StringBuildersb = new StringBuilder("[");   //组拼json格式数据
           for(News n :ns){
              sb.append("{");
              sb.append("id:").append(n.getId()).append(",");
              sb.append("name:\"").append(n.getName()).append("\",");
              sb.append("timeLength:").append(n.getTimeLength());
              sb.append("},");           
           }                
           sb.deleteCharAt(sb.length()-1);
           sb.append("]");
           request.setAttribute("json", sb.toString());
           request.getRequestDispatcher("/WEB-INF/Jnews.jsp").forward(request, response);
       }else{
       request.setAttribute("ns", ns);
       request.getRequestDispatcher("/WEB-INF/news.jsp").forward(request, response);
       }
    }
    public voiddoPost(HttpServletRequest request, HttpServletResponse response)
           throws ServletException,IOException {
       doGet(request,response);
    } 
}

 

转发的jsp

News.jsp

<?xml version="1.0"encoding="UTF-8"?><%@ page language="java" import="java.util.*"pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"prefix="c"%>
<vedionews>
    <c:forEach  items="${ns}"var="news">
       <news id="${news.id}">
           <name>${news.name}</name>
           <timelength>${news.timeLength}</timelength>
       </news>
    </c:forEach>
</vedionews>

Json格式数据

JNews.jsp

<%@ page language="java"import="java.util.*" pageEncoding="UTF-8" contentType="text/plain;charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"prefix="c"%>
${json}

Android客户端


目录结构


布局文件:

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
   
    <ListView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/listView"
        ></ListView>
</LinearLayout>

Items.xml

<?xml version="1.0"encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
   
    <TextView
    android:layout_width="80px"
    android:layout_height="wrap_content"
    android:id="@+id/name"
        />
   
    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/timeLength"
        />
    
</LinearLayout>

News.java

public class News {
 
    private int id;
    private String name;
    private Integer timeLength;
 
    public News() {
    }
 
    public News(int id, String name, int timeLength) {
       this.id = id;
       this.name = name;
       this.timeLength = timeLength;
    }
 
    public int getId() {
       return id;
    }
 
    public void setId(int id) {
       this.id = id;
    }
 
    public String getName() {
       return name;
    }
 
    public void setName(String name){
       this.name = name;
    }
 
    public IntegergetTimeLength() {
       return timeLength;
    }
 
    public voidsetTimeLength(Integer timeLength) {
       this.timeLength = timeLength;
    }
 
}


MainActivity

public class MainActivity extends Activity {
   
    private VedioNewsService service = new  VedioNewsService();
 
    @Override
    protected void onCreate(BundlesavedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
      
       ListViewlistView = (ListView) this.findViewById(R.id.listView);
       try {
//         List<News>ns = service.getUpdateNews();         //通过服务类获取xml数据 
           List<News>ns = service.getUpdateNewsJson();     //通过服务类获取json数据
           List<Map<String,Object>>data = new ArrayList<Map<String,Object>>();
           for(News n :ns){
              Map<String,Object>m = new HashMap<String, Object>();
              m.put("id", n.getId());
              m.put("name", n.getName());
              m.put("timeLength", n.getTimeLength());
              Log.i("onCreate", n.getName()+"000");
              data.add(m);
           }  
	   //创建适配器,处理数据
           SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.items, new String[]{"name","timeLength"}, new int[]{R.id.name,R.id.timeLength});
           listView.setAdapter(adapter);
          
       }catch (Exception e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
    }
}


 

Service类

public class VedioNewsService {
    /**
     * 获取新闻更新的信息__xml
     * @return   新闻信息
     * @throws IOException
     * @throws XmlPullParserException
     */
    public List<News>getUpdateNews() throws IOException, XmlPullParserException{
 
       URLurl = new URL("http://172.16.121.10:8080/VedioNews/servlet/ListNewsServlet");
       HttpURLConnectionconn =  (HttpURLConnection)url.openConnection();
       conn.setConnectTimeout(5000);
       conn.setRequestMethod("GET");
       if(conn.getResponseCode()== 200){
           InputStreamin = conn.getInputStream();
           return parseNews(in);
       }
       return null;
    }
   
    /**
     * 获取新闻更新的信息__json
     * @return   新闻信息
     * @throws IOException
     * @throws XmlPullParserException
     */
    public List<News>getUpdateNewsJson() throws Exception {
       URLurl = new URL("http://172.16.121.10:8080/VedioNews/servlet/ListNewsServlet?format=json");
       HttpURLConnectionconn =  (HttpURLConnection)url.openConnection();
       conn.setConnectTimeout(5000);
       conn.setRequestMethod("GET");
       if(conn.getResponseCode()== 200){
           InputStreamin = conn.getInputStream();
           return parseNews(in);
       }
       return null;
    }
   
    /**
     * 解析json数据
     * @param输入流
     * @return  
     * @throws Exception
     */
    private List<News> parseJson(InputStreamin) throws Exception {
       byte[] data = StreamTool.read(in);
       List<News>list = new ArrayList<News>();
       Stringjson = new String(data);
       Log.i("xxxx", json);
       JSONArrayarray = new JSONArray(json);    //json数据构造成json数组对象
       for(int i =0;i<array.length();i++){
           JSONObjecto =  array.getJSONObject(i);   //获得具体索引值得json对象
           Newsnews = new News(o.getInt("id"),o.getString("name"),o.getInt("timeLength"));
           list.add(news);     
       }  
       return list;
    }
      
    /**
     * pull解析xml文档
     * @param输入流
     * @return
     * @throws XmlPullParserException
     * @throws IOException
     */
    private List<News>parseNews(InputStream in) throws XmlPullParserException, IOException {
 
       List<News>ns = new ArrayList<News>();
       Newsnews = null;
 
       XmlPullParserparse = Xml.newPullParser();
       parse.setInput(in,"UTF-8");
       int event =parse.getEventType();
       while(event !=XmlPullParser.END_DOCUMENT){    
           switch (event) {
           case XmlPullParser.START_TAG:
              if(parse.getName().equals("news")){
                  int id = newInteger(parse.getAttributeValue(0));
                  news= new News();
                  news.setId(id);                
              }else if(parse.getName().equals("name")){
                  news.setName(parse.nextText());
              }else if(parse.getName().equals("timelength")){
                  news.setTimeLength(newInteger(parse.nextText()));
              }
              break;
           case XmlPullParser.END_TAG:
              if(parse.getName().equals("news")){
                  ns.add(news);
                  news=null;
              }
              break;
           }
           event= parse.next();
       }
       return ns;
    }
 
}

工具类:

public class StreamTool {
 
    public static byte[] read(InputStreamin) throws Exception {
      
       ByteArrayOutputStreamout = new ByteArrayOutputStream();
       byte[] buffer = new byte[1024];
       int len = 0 ;
      
       while((len =in.read(buffer)) != -1){
           out.write(buffer,0, len);
       }
       in.close();
      
       return out.toByteArray();
    }
 
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值