这次简单的通过使用okhttp和node.js来实现Android与服务端交互。
使用node.js作为服务端是因为其配置和开发都比较简便,在windows平台上也能很快搭建起环境;
在开发Android应用时,这种快速构建的“后端”,可以用来在真正的服务端开发完成前,Mock后端数据,来验证应用网络接口的正确性。
node.js的安装过程很简单,在此就略过了,直接进入代码编写^_^
首先来写“后端”的程序逻辑,在这里我们假设3个不同的请求响应:
1.返回一端普通文本
2.返回json数据
3.异常资源返回404错误
testServer.js
文件:
var http = require("http")
var url = require("url")
// 将请求资源封装在这个对象中,来简化不同url资源访问逻辑
// 借鉴自这篇教程:http://www.nodebeginner.org/index-zh-cn.html
var handle = {}
handle["/"] = mainResponse
handle["/getexample"] = getExampleResponse
handle["/getjsonexample"] = getJsonResponse
// 整个后端逻辑封装到一个函数中
function start() {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname
console.log("pathname is: " + pathname)
if (pathname == "/favicon.ico") { // 用浏览器调试时忽略掉favicon.ico图标的请求
return
} else if (typeof handle[pathname] === "function") { // 请求url与handle配置相同时,执行相应函数
handle[pathname](response)
} else { // 未知url资源返回404页面
response.writeHead(404, {
"Content-Type": "text/plain"})
response.write("404 page not found")
response.end()
}
}
http.createServer(onRequest).listen(