首页 > 代码库 > Android客户端与云服务器进行网络通信
Android客户端与云服务器进行网络通信
多写技术文档,多写技术文档,多写技术文档,重要的事情说三遍......
-------------------------------------------------------------------------------------------------------------------
功能需求:Android客户端解析和显示云服务器返回的xml文件。
思路:涉及到Android端应用和Java ee端web应用的编码实现。
示例:Android客户端获取腾讯云服务器上的视频资讯
步骤:
1、开发环境部署
Java ee部分:
java+apache-tomcat-8.5.9-windows-x64+Eclipse(for javaEE Developers版本)
android部分:
androidstudio集成开发工具
2、web应用部分开发
a、在Java ee下新建“Dynamic Web Project”;
b、然后新建一个servlet,同时注意web.xml中的相关配置情况,截图如下:
(注:servlet是放在HTTP Web服务器上面运行的Java程序。当用户通过客户端和服务器交互时,请求(request)会送给web服务器。如果请求需要Java的servlet时,服务器会执行或调用已经执行的servlet程序代码。servlet只是在服务器上运行的程序代码,执行用户发出请求所要的结果。)
c、其中servlet核心代码如下:
public class ListServelet extends HttpServlet { private static final long serialVersionUID = 1L; private VideoNewsService service=new VideoNewsServiceBean(); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<News> videos = service.getLastNews(); request.setAttribute("videos", videos); request.getRequestDispatcher("/WEB-INF/page/videonews.jsp").forward(request, response); } }
新建一个javabean,代码如下:资讯id+标题+时长
public class VideoNewsServiceBean implements VideoNewsService { public List<News> getLastNews(){ List<News> newes = new ArrayList<News>(); newes.add(new News(90, "喜羊羊与灰太狼全集", 78)); newes.add(new News(10, "实拍舰载直升东海救援演习", 28)); newes.add(new News(56, "喀麦隆VS荷兰", 70)); return newes; } }
在业务bean中定义一个方法返回一个集合,例如:News,集合存放了数据库最新的视频资讯,集合里的元素类型采用一个javabean描述每一条视频资讯。
public class News { private Integer id; private String title; private Integer timelength; public News(Integer id, String title, Integer timelength) { this.id = id; this.title = title; this.timelength = timelength; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Integer getTimelength() { return timelength; } public void setTimelength(Integer timelength) { this.timelength = timelength; } }
此外,Java ee是面向接口编程,将业务bean中的方法进行接口抽取,同时继承实现这个接口中的方法。接口代码如下:
public interface VideoNewsService { /** * 获取最新的视频资讯 * @return */ public List<News> getLastNews(); }
e、 另外在表现层构造xml数据,在WebContent-WEB-INF下新建一个“page”文件夹,然后再新建一个jsp文件,名称“videonews”。contentType=“text/xml” ,代码如下:
1 <%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><?xml version="1.0" encoding="UTF-8"?> 2 <videonews><c:forEach items="${videos}" var="video"> 3 <news> 4 <id>${video.id}</id> 5 <title>${video.title}</title> 6 <timelength>${video.timelength}</timelength> 7 </news></c:forEach> 8 </videonews>
其中xml数据的呈现形式可以在jsp文件中进行定义,同时需要在lib文件下添加第三方类库jstl,如下:
f、在servlet中需要引入新建的jsp文件,这样才能自定义xml格式文件,如下:
其中集合中的视频资讯对象传递给jsp文件,把对象放在request范围给定key,接着把请求内部转发给jsp。指定jsp文件路径。
g、在javaee下把应用部署到tomcat服务器之后,在浏览器中输入路径:http://localhost:8080/videonews/ListServlet出现xml数据格式,证明web应用没问题了,即从服务器端返回了xml格式的数据并且显示在屏幕上。
3、Android部分开发
a、引入OkHttp来发送HTTP请求方式,在build.gradle添加OkHttp依赖文件,如下:
dependencies { compile fileTree(dir: ‘libs‘, include: [‘*.jar‘]) androidTestCompile(‘com.android.support.test.espresso:espresso-core:2.2.2‘, { exclude group: ‘com.android.support‘, module: ‘support-annotations‘ }) compile ‘com.android.support:appcompat-v7:25.0.1‘ testCompile ‘junit:junit:4.12‘ compile ‘com.squareup.okhttp3:okhttp:3.4.1‘ }
b、此外,android部分的核心是对xml数据进行解析,代码如下:
1 class VideoNewsService { 2 /** 3 * 获取视频资讯 4 * 5 * @return 6 * @throws Exception 7 */ 8 static List<News> newses = new ArrayList<>(); 9 static List<News> sendRequestWithOkHttp() { 10 new Thread(new Runnable() { 11 @Override 12 public void run() { 13 try { 14 OkHttpClient client = new OkHttpClient(); 15 Request request = new Request.Builder() 16 // 指定访问的服务器地址是电脑本机 17 .url("http://云服务器公网IP:8080/VideoNews/ListServelet") 18 .build(); 19 Response response = client.newCall(request).execute(); 20 String responseData =http://www.mamicode.com/ response.body().string(); 21 parseXML(responseData); 22 23 } catch (Exception e) { 24 e.printStackTrace(); 25 } 26 } 27 }).start(); 28 return newses; 29 } 30 31 private static List<News> parseXML(String xmlData) throws Exception { 32 News news = null; 33 XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 34 XmlPullParser parser = factory.newPullParser(); 35 parser.setInput(new StringReader(xmlData)); 36 int event = parser.getEventType(); 37 while (event != XmlPullParser.END_DOCUMENT) { 38 switch (event) { 39 case XmlPullParser.START_TAG:
40
41 if ("id".equals(parser.getName())) { 42 int id = Integer.valueOf(parser.nextText()); 43 news = new News(); 44 news.setId(id); 45 } else if ("title".equals(parser.getName())) { 46 news.setTitle(parser.nextText()); 47 } else if ("timelength".equals(parser.getName())) { 48 news.setTimelength(Integer.valueOf(parser.nextText())); 49 } 50 break; 51 52 case XmlPullParser.END_TAG: { 53 if ("news".equals(parser.getName())) { 54 newses.add(news); 55 news = null; 56 } 57 break; 58 } 59 default: 60 break; 61 } 62 event = parser.next(); 63 } 64 return newses; 65 } 66 }
News.java代码如下:
1 public class News { 2 private Integer id; 3 private String title; 4 private Integer timelength; 5 public News(){} 6 public News(Integer id, String title, Integer timelength) { 7 this.id = id; 8 this.title = title; 9 this.timelength = timelength; 10 } 11 public Integer getId() { 12 return id; 13 } 14 public void setId(Integer id) { 15 this.id = id; 16 } 17 public String getTitle() { 18 return title; 19 } 20 public void setTitle(String title) { 21 this.title = title; 22 } 23 public Integer getTimelength() { 24 return timelength; 25 } 26 public void setTimelength(Integer timelength) { 27 this.timelength = timelength; 28 } 29 30 }
MainActivty.class的核心代码如下:
1 public class MainActivity extends AppCompatActivity { 2 /** Called when the activity is first created. */ 3 @Override 4 public void onCreate(Bundle savedInstanceState) { 5 super.onCreate(savedInstanceState); 6 setContentView(R.layout.activity_main); 7 8 ListView listView = (ListView) this.findViewById(R.id.listView); 9 10 try { 11 List<News> videos = VideoNewsService.sendRequestWithOkHttp();//需修改成你本机的Http请求路径 12 List<HashMap<String, Object>> data = http://www.mamicode.com/new ArrayList<HashMap<String,Object>>(); 13 for(News news : videos){ 14 HashMap<String, Object> item = new HashMap<String, Object>(); 15 item.put("id", news.getId()); 16 item.put("title", news.getTitle()); 17 item.put("timelength", getResources().getString(R.string.timelength) 18 + news.getTimelength()+ getResources().getString(R.string.min)); 19 data.add(item); 20 } 21 SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item, 22 new String[]{"title", "timelength"}, new int[]{R.id.title, R.id.timelength}); 23 listView.setAdapter(adapter); 24 } catch (Exception e) { 25 e.printStackTrace(); 26 } 27 } 28 }
c、最终运行成功的效果图,如下:
--------------------------------------------------------------------------------------------------------------------
参考资料:
http://www.cnblogs.com/diyunfei/p/6826557.html //怎样将本地web项目部署到腾讯云服务器上?
https://jingyan.baidu.com/article/3a2f7c2e62d25e26afd611fa.html //WIN7系统JavaEE(java+tomcat7+Eclipse)环境配置
Android客户端与云服务器进行网络通信