android端从服务器抓取的几种常见的数据的处理方式

1、图片

public void look(View v) {
		String path = et_path.getText().toString();

		try {
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5000);
			if(conn.getResponseCode() == 200){
				InputStream is = conn.getInputStream();
				Bitmap bitmap = BitmapFactory.decodeStream(is);
				if(bitmap != null){
					iv.setImageBitmap(bitmap);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


2、网页源码

public void look(View v) {
		String path = et_path.getText().toString();

		try {
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5000);
			
			if(conn.getResponseCode() == 200){
				InputStream is = conn.getInputStream();
				
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int len = 0;
				
				//把流转化成文本信息
				while((len = is.read(buffer)) != -1){
					bos.write(buffer,0,len);
				}
				
				String html  = bos.toString();
				html_tv.setText(html);
				
				is.close();
				bos.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


3、Xml形式的数据

public List<HeaderNew> getHeaderNews(Context context) throws Exception{
		
		String path = context.getResources().getString(R.string.serverurl);
		
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(5000);
		
		if(conn.getResponseCode() == 200){
			InputStream is = conn.getInputStream();
			return parserHeaderNews(is);
		}
		
		return null;
	}

	public List<HeaderNew> parserHeaderNews(InputStream is) throws Exception {
		List<HeaderNew> headerNews = null;
		HeaderNew headerNew = null;
		
		XmlPullParser parser = Xml.newPullParser();
	    
		parser.setInput(is,"UTF-8");
		
		int eventType = parser.getEventType();
		
		while(eventType != XmlPullParser.END_DOCUMENT){
			switch(eventType){
			case XmlPullParser.START_TAG:
				if("HeaderNews".equals(parser.getName())){
					headerNews = new ArrayList<HeaderNew>();
				}else if("HeaderNew".equals(parser.getName())){
					headerNew = new HeaderNew();
				}else if("image".equals(parser.getName())){
					headerNew.setImage(parser.nextText());
				}else if("title".equals(parser.getName())){
					headerNew.setTitle(parser.nextText());
				}else if("content".equals(parser.getName())){
					headerNew.setContent(parser.nextText());
				}else if("count".equals(parser.getName())){
					headerNew.setCount(parser.nextText());
				}
				break;
			case XmlPullParser.END_TAG:
				if("HeaderNew".equals(parser.getName())){
					headerNews.add(headerNew);
					headerNew = null;
				}
				break;
			default:
				break;
			}
			
			eventType = parser.next();
		}
		
		return headerNews;
	}


4、抓取JSON格式的数据

抓取JSON格式的数据是以抓取网页源码为基础的。

public List<HeaderNew> getHeaderNewsFromJSON(Context context) throws Exception{
		List<HeaderNew> headerNews = new ArrayList<HeaderNew>();
		
		String path = context.getResources().getString(R.string.serverurl_json);
		
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(5000);
		if(conn.getResponseCode() == 200){
			InputStream is = conn.getInputStream();
			
			
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while((len = is.read(buffer)) != -1){
				bos.write(buffer,0,len);
			}
			String json = bos.toString();
			
			JSONArray jsonArray = new JSONArray(json);
			
			for(int i = 0 ; i < jsonArray.length() ; ++i){
				JSONObject jsonObject = (JSONObject) jsonArray.get(i);
				HeaderNew headerNew = new HeaderNew();
				
				headerNew.setImage(jsonObject.getString("image"));
				headerNew.setTitle(jsonObject.getString("title"));
				headerNew.setContent(jsonObject.getString("content"));
				headerNew.setCount(jsonObject.getString("count"));
				
				headerNews.add(headerNew);
			}
		}
		
		return headerNews;
	}


5、抓取Xml形式的数据与抓取JSON形式的数据的区别

构建时的区别:

1)Xml形式的数据

    服务器端直接返回数据集合,由JSP来构建XML形式的数据

代码如下:

 servlet:

public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		HeaderNewsService service = new HeaderNewsService();
		List<HeaderNew> headerNews = service.getHeaderNews();
		
		request.setAttribute("headerNews", headerNews);
		request.getRequestDispatcher("/WEB-INF/page/headernewsxml1.jsp").forward(request, response);
	}

jsp:

<?xml version="1.0" encoding="UTF-8"?>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page contentType="text/html; charset=utf-8" %>
<HeaderNews>
  <c:forEach items="${headerNews}" var="headerNew">
    <HeaderNew>
       <image>${headerNew.image }</image>
       <title>${headerNew.title }</title>
       <content>${headerNew.content}</content>
       <count>${headerNew.count}</count>
    </HeaderNew>
  </c:forEach>
</HeaderNews>



2)JSON形式的数据

在服务器端构造好JSON格式的数据。JSP页面直接显示即可。

代码如下:

public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		HeaderNewsService service = new HeaderNewsService();
		List<HeaderNew> headerNews = service.getHeaderNews();
		StringBuilder sb = new StringBuilder("[");
		
		for(HeaderNew headerNew : headerNews){
			sb.append("{");
			sb.append("image:").append("\"").append(headerNew.getImage()).append("\"").append(",");
			sb.append("title:").append("\"").append(headerNew.getTitle()).append("\"").append(",");
			sb.append("content:").append("\"").append(headerNew.getContent()).append("\"").append(",");
			sb.append("count:").append("\"").append(headerNew.getCount()).append("\"");
			sb.append("}");
			sb.append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		sb.append("]");
		
		String json = sb.toString();
		request.setAttribute("json",json);
		request.getRequestDispatcher("/WEB-INF/page/headernewsjson.jsp").forward(request,response);
	}

JSP:

<%@ page contentType="text/html; charset=UTF-8" %>
${json}


附上JSON数据的格式:

[{ a : b , c : d }  , {.....}]







你可能感兴趣的:(android端从服务器抓取的几种常见的数据的处理方式)