今天终于把老大交代的任务搞完了,感觉收获挺多的,所以就写一篇来记录一下吧,首先还是来看一下,老大们的需求

需求:

希望移动端的用户标识(IMEI)和HTML页面的用户标识(Cookie)连接起来,其中HTML页面可能是用户使用PC访问指定的html页面也有可能是移动端使用浏览器访问html页面

技术解决:

运用移动设备的系统特型,用Apps的Service监听本地的网络端口,当局域网内或本机的Html页面通过请求调用本地IP:Port时触发监听。Apps在将当前Html的Cookie和移动设备标识物发回服务端时,即实现了本次PC/Mobile Html页面的Cookie和移动设备的互相绑定。

具体实现方案之多端通信技术方案



各模块细节

1.Native App(移动端的app):

1).跟随主服务常驻内存,在收到当前网络环境为Wifi事件后,启动HttpServer。

(当前网络切换成3G/2G等网络时关闭HttpServer)。

以上这步我们叫做注册:启动移动端的HttpServer的时候,我们会将移动设备的ip地址(内网地址)发送到指定的后台Server上

 

2).收到从Web来的http请求后,往Server发送绑定请求,这时候就将移动端的IMEI和HTML中的Cookie一起上传到指定的Server上

例如:

http://serverhost/?cookie=123213&imei=31233213123

以上这步我们叫做一次绑定的完成操作

以为我们是在移动端开始一个HttpServer的,所以要考虑一些额外的因素,比如耗电量

风险控制:使用灰度测试规则,并使用开关限制功能。

功耗风险:经过三台设备测试,电量消耗忽略不计(具体CPU使用时间在统计)。

 

2.Web JS:

1).加载页面加载后先从CDN加载一个静态的JS到此页面。

2).静态JS再请求Server 获取一段动态JS用以做本地Ping。

(如果此IP已有N次获取,则考虑>N的节点是一个大型公共网络,则把此公共IP加入黑名单,不再返回动态JS)

3).获得动态JS后直接Ping本地的HttpServer。

(Ping的IP/Port会随着动态JS一起下发)

这里我们是在Html页面中使用JS脚本来处理传递Cookie给移动端的功能。

3.Bridge Server:

1).Sever选型:Node.js

同时考虑到开发效率,性能,和client的JS的契合度。

Node.js单台16核服务器,4节点,QPS经测试能到6k-8k。

较适合短频非阻塞的请求。

 

2).数据存储:Redis

考虑到NativeApp的外网IP时效性,以及对于短频请求的快速应答。

以外网IP为Key,各个IP为Value。每天清理一次外网IP。

存储格式:{外网IP:{NativeApp IP/Port, .........}}



3).移动端所需要的接口

接口一:Native App 对于本外网IP的注册的请求。

接口二:Navtive App的绑定请求。



具体原理图:





上面讲解了一下技术的实现方案,下面我们就来看一下,具体的实现技术

首先来看移动端的,我们需要建立一个HttpServer

我们可能知道在PC端建立一个Server很简单,直接使用Tomcat服务器就可以了,但是我们移动端不可能去搭建一个服务器的,那么我们该怎么办呢?我们可以在网上搜索一下关于如何在手机中搭建一个WebServce,我们可以看到Apache已经帮我们做好了这件事了,他提供了一个jar,有相应的api,同时还有一种技术就是老外有个人写好了一个类:NanoHttpd,我们只需要看懂这个类,然后自己在编写一个类,继承这个类即可,因为这个类是抽象的。这两种搭建的Server原理都是很简单的,就是建立一个Socket连接,这个和Tomcat是一样的,只是他们将这种操作进行优化处理了,那么我们首先来看一下Apache给我们提供的这个HttpServer:

按照上面的技术方案,我们希望这个HttpServer常驻在一个服务中进行监听的,所以我们需要建立一个Service

  1. package com.sohu.tests;
  2.  
  3. import java.io.IOException;
  4.  
  5. import org.apache.http.client.ClientProtocolException;
  6.  
  7. import android.app.Service;
  8. import android.content.BroadcastReceiver;
  9. import android.content.Context;
  10. import android.content.Intent;
  11. import android.content.IntentFilter;
  12. import android.net.ConnectivityManager;
  13. import android.os.IBinder;
  14. import android.util.Log;
  15.  
  16. public class SocketService extends Service {
  17.  
  18. private int port = Consts.defaultPort;
  19.  
  20. //网络开关状态改变的监听
  21. private BroadcastReceiver receiver = new BroadcastReceiver() {
  22. @Override
  23. public void onReceive(Context context, Intent intent) {
  24. if(intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)){
  25. AppListYPLog.e("DEMO","网络状态切换...");
  26. //注册接口
  27. new Thread(){
  28. @Override
  29. public void run(){
  30. //开始注册
  31. register();
  32. }
  33. }.start();
  34. }
  35. }
  36. };
  37.  
  38. @Override
  39. public IBinder onBind(Intent arg0) {
  40. return null;
  41. }
  42.  
  43. @Override
  44. public void onCreate() {
  45. super.onCreate();
  46. Log.v("23233", "Complete");
  47.  
  48. Utils.init(this);
  49.  
  50. //开启监听端口
  51. HttpServer hs = new HttpServer();
  52. try{
  53. AppListYPLog.i("监听开启...");
  54. for(int i=0;i<Consts.portAry.length;i++){
  55. if(Utils.checkPort(Consts.portAry[i])){
  56. port = Consts.portAry[i];
  57. break;
  58. }
  59. }
  60. hs.execute(port);
  61. register();
  62. }catch(Exception e){
  63. AppListYPLog.e("异常:"+e.getMessage());
  64. }
  65.  
  66. //注册广播
  67. IntentFilter filter = new IntentFilter();
  68. filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
  69. registerReceiver(receiver, filter);
  70.  
  71. }
  72.  
  73. /**
  74. * 注册ip地址
  75. * @return
  76. */
  77. public boolean register(){
  78. //拼接参数
  79. StringBuilder param = new StringBuilder();
  80. param.append("imei=");
  81. param.append(Utils.getImeiInfo());
  82. param.append("&hs_ip=");
  83. param.append(Utils.getLocalHostIp()+":"+port);
  84. param.append("&route_mac=");
  85. param.append(Utils.getRouteMac());
  86. param.append("&route_ssid=");
  87. param.append(Utils.getRouteSSID());
  88. param.append("&timetag=");
  89. param.append(System.currentTimeMillis()+"");
  90.  
  91. boolean flag = false;
  92.  
  93. //上报数据
  94. if(Utils.checkNetWorkState()){
  95. try {
  96. flag = NetUtils.uploadRequest(Consts.registerUrl, param.toString());
  97. if(flag){
  98. AppListYPLog.i("注册操作成功");
  99. //Toast.makeText(getApplicationContext(), "注册成功", Toast.LENGTH_LONG).show();
  100. }else{
  101. AppListYPLog.e("注册操作失败");
  102. //Toast.makeText(getApplicationContext(), "注册失败", Toast.LENGTH_LONG).show();
  103. }
  104. } catch (ClientProtocolException e) {
  105. AppListYPLog.e("异常:"+e.getMessage()+",注册失败");
  106. } catch (IOException e) {
  107. AppListYPLog.e("异常:"+e.getMessage()+",注册失败");
  108. } catch(Exception e){
  109. AppListYPLog.e("异常:"+e.getMessage()+",注册失败");
  110. }
  111. }
  112.  
  113. return flag;
  114. }
  115.  
  116. }

在这个服务中,我们开始的时候就进行注册,上报一些信息:

imei:手机移动的标识

hs_ip:手机的HttpServer的地址和端口号

route_mac:手机连接的路由器的mac地址

route_ssid:手机连接的路由器的ssid

timetag:注册的时间戳

同时我们还注册了一个监听网络变化的广播,这个是为了防止,开始的时候用户没有开启网络,一旦用户开启网路的时候,我们就开启监听并且进行注册。

这里我们使用的监听端口是3个,因为我们知道,端口最大的是655535,0-1024是系统使用的,所以我们就使用了三个备用的端口,在使用这个端口之前要检测一下该端口有没有被占用,这里我们就使用Socket探针技术。

再来看一下最核心的HttpServer的实现:

首先我们需要下载Apache提供的jar包:

http://download.csdn.net/detail/jiangwei0910410003/7431829



代码:

  1. package com.sohu.tests;
  2.  
  3. import java.io.IOException;
  4. import java.io.InterruptedIOException;
  5. import java.net.ServerSocket;
  6. import java.net.Socket;
  7. import java.util.Locale;
  8.  
  9. import java.util.Map;
  10.  
  11. import org.apache.http.ConnectionClosedException;
  12. import org.apache.http.HttpException;
  13. import org.apache.http.HttpRequest;
  14. import org.apache.http.HttpResponse;
  15. import org.apache.http.HttpResponseInterceptor;
  16. import org.apache.http.HttpServerConnection;
  17. import org.apache.http.HttpStatus;
  18. import org.apache.http.MethodNotSupportedException;
  19. import org.apache.http.entity.StringEntity;
  20. import org.apache.http.impl.DefaultConnectionReuseStrategy;
  21. import org.apache.http.impl.DefaultHttpResponseFactory;
  22. import org.apache.http.impl.DefaultHttpServerConnection;
  23. import org.apache.http.params.BasicHttpParams;
  24. import org.apache.http.params.CoreConnectionPNames;
  25. import org.apache.http.params.CoreProtocolPNames;
  26. import org.apache.http.params.HttpParams;
  27. import org.apache.http.protocol.BasicHttpContext;
  28. import org.apache.http.protocol.HttpContext;
  29. import org.apache.http.protocol.HttpProcessor;
  30. import org.apache.http.protocol.HttpRequestHandler;
  31. import org.apache.http.protocol.HttpRequestHandlerRegistry;
  32. import org.apache.http.protocol.HttpService;
  33. import org.apache.http.protocol.ImmutableHttpProcessor;
  34. import org.apache.http.protocol.ResponseConnControl;
  35. import org.apache.http.protocol.ResponseContent;
  36. import org.apache.http.protocol.ResponseDate;
  37. import org.apache.http.protocol.ResponseServer;
  38.  
  39. public class HttpServer {
  40.  
  41. //获取来访者的ip地址
  42. private static String ipAddress = "";
  43.  
  44. //开启监听
  45. public void execute(int port) throws Exception{
  46. Thread t = new RequestListenerThread(port);
  47. t.setDaemon(false);
  48. t.start();
  49. }
  50.  
  51. //自定义HttpRequest的处理类,我们需要继承HttpRequestHandler接口
  52. static class WebServiceHandler implements HttpRequestHandler {
  53.  
  54. public WebServiceHandler() {
  55. super();
  56. }
  57.  
  58. //在这个方法中我们就可以处理请求的业务逻辑
  59. public void handle(final HttpRequest request,
  60. final HttpResponse response, final HttpContext context)
  61. throws HttpException, IOException {
  62.  
  63. //获取请求方法
  64. String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
  65. //获取请求的uri
  66. String target = request.getRequestLine().getUri();
  67. Map<String,String> params = Utils.getParam(target);
  68. //拼接参数
  69. StringBuilder param = new StringBuilder();
  70. param.append("cookie=");
  71. if(params.get("cookie") != null){
  72. param.append(params.get("cookie"));
  73. }
  74. param.append("&imei=");
  75. param.append(Utils.getImeiInfo());
  76. param.append("&visitor_ip=");
  77. param.append(ipAddress);
  78. param.append("&local_ip=");
  79. param.append(Utils.getLocalHostIp());
  80. param.append("&route_mac=");
  81. param.append(Utils.getRouteMac());
  82. param.append("&route_ssid=");
  83. param.append(Utils.getRouteSSID());
  84. param.append("&timetag=");
  85. param.append(System.currentTimeMillis()+"");
  86.  
  87. //上报数据
  88. try{
  89. if(Utils.checkNetWorkState()){
  90. boolean flag = NetUtils.uploadRequest(Consts.cookieUrl, param.toString());
  91. if(flag){
  92. AppListYPLog.e("完成操作成功");
  93. }else{
  94. AppListYPLog.e("完成操作失败");
  95. }
  96. }
  97. }catch(Exception e){
  98. AppListYPLog.e("异常:"+e.getMessage()+"完成操作失败");
  99. }
  100.  
  101. //get请求方式(我们这里只处理get方式)
  102. if (method.equals("GET") ) {
  103. response.setStatusCode(HttpStatus.SC_OK);
  104. StringEntity entity = new StringEntity("Request Success!!");
  105. response.setEntity(entity);
  106. } else if (method.equals("POST") ) {
  107. response.setStatusCode(HttpStatus.SC_OK);
  108. StringEntity entity = new StringEntity("Request Success!!");
  109. response.setEntity(entity);
  110. } else {
  111. throw new MethodNotSupportedException(method + " method not supported");
  112. }
  113. }
  114.  
  115. }
  116.  
  117. /**
  118. * 自定一个监听的线程
  119. * @author weijiang204321
  120. *
  121. */
  122. static class RequestListenerThread extends Thread {
  123.  
  124. private final ServerSocket serversocket;
  125. private final HttpParams params;
  126. private final HttpService httpService;
  127.  
  128. public RequestListenerThread(int port)
  129. throws IOException {
  130.  
  131. /**********************下面就是模板代码了***********************/
  132. this.serversocket = new ServerSocket(port);
  133.  
  134. HttpProcessor httpproc = new ImmutableHttpProcessor(
  135. new HttpResponseInterceptor[] {
  136. new ResponseDate(), new ResponseServer(),
  137. new ResponseContent(), new ResponseConnControl() });
  138. this.params = new BasicHttpParams();
  139. this.params
  140. .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
  141. .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE,8 * 1024)
  142. .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
  143. .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
  144. .setParameter(CoreProtocolPNames.ORIGIN_SERVER,"HttpComponents/1.1");
  145.  
  146. //这只请求头信息
  147. HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
  148. //WebServiceHandler用来处理webservice请求,这里我们可以注册多个处理器Handler的
  149. reqistry.register("*", new WebServiceHandler());
  150.  
  151. this.httpService = new HttpService(httpproc,
  152. new DefaultConnectionReuseStrategy(),
  153. new DefaultHttpResponseFactory());
  154. httpService.setParams(this.params);
  155. //为http服务设置注册好的请求处理器。
  156. httpService.setHandlerResolver(reqistry);
  157.  
  158. }
  159.  
  160. @Override
  161. public void run() {
  162. AppListYPLog.i("Listening on port " + this.serversocket.getLocalPort());
  163. AppListYPLog.i("Thread.interrupted = " + Thread.interrupted());
  164. while (!Thread.interrupted()) {
  165. try {
  166. // 建立Http连接
  167. Socket socket = this.serversocket.accept();
  168. DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
  169. ipAddress = socket.getInetAddress().getHostAddress();
  170. AppListYPLog.i("Incoming connection from " + socket.getInetAddress());
  171. conn.bind(socket, this.params);
  172. //开启工作线程
  173. Thread t = new WorkerThread(this.httpService, conn);
  174. t.setDaemon(true);
  175. t.start();
  176. } catch (InterruptedIOException ex) {
  177. AppListYPLog.e("异常:InterruptedIOException");
  178. break;
  179. } catch (IOException e) {
  180. AppListYPLog.e("I/O error initialising connection thread: " + e.getMessage());
  181. break;
  182. }
  183. }
  184. }
  185. }
  186.  
  187. /**
  188. * 后台工作线程
  189. * @author weijiang204321
  190. *
  191. */
  192. static class WorkerThread extends Thread {
  193.  
  194. private final HttpService httpservice;
  195. private final HttpServerConnection conn;
  196.  
  197. public WorkerThread(final HttpService httpservice,final HttpServerConnection conn) {
  198. super();
  199. this.httpservice = httpservice;
  200. this.conn = conn;
  201. }
  202.  
  203. @Override
  204. public void run() {
  205. System.out.println("New connection thread");
  206. HttpContext context = new BasicHttpContext(null);
  207. try {
  208. while (!Thread.interrupted() && this.conn.isOpen()) {
  209. this.httpservice.handleRequest(this.conn, context);
  210. }
  211. } catch (ConnectionClosedException ex) {
  212. System.err.println("Client closed connection");
  213. } catch (IOException ex) {
  214. System.err.println("I/O error: " + ex.getMessage());
  215. } catch (HttpException ex) {
  216. System.err.println("Unrecoverable HTTP protocol violation: "+ ex.getMessage());
  217. } finally {
  218. try {
  219. this.conn.shutdown();
  220. } catch (IOException ignore) {
  221. }
  222. }
  223. }
  224. }
  225.  
  226. }

我们首先需要定义一个RequestHander用来处理请求的逻辑结果,同时我们需要建立一个HttpConnection,这里我们需要获取来访者的ip地址,所以我们定义了一个全局的变量ipAddress,然后在WebServiceHandler类中的handle方法中进行上报完成的动作,需要上报的参数为:

cookie:来访者携带的cookie值(也就是Html页面中的cookie)

imei:手机的移动标识

visitor_ip:来访者的ip地址

local_ip:本机的ip地址

route_mac:手机连接的路由器的地址

route_ssid:手机连接的路由器的ssid

timetag:上报的时间戳

下面再来看一下辅助类

Utils:

  1. package com.sohu.tests;
  2.  
  3. import java.io.IOException;
  4. import java.net.InetAddress;
  5. import java.net.NetworkInterface;
  6. import java.net.Socket;
  7. import java.net.SocketException;
  8. import java.net.UnknownHostException;
  9. import java.util.Enumeration;
  10. import java.util.HashMap;
  11. import java.util.Map;
  12.  
  13. import org.apache.http.conn.util.InetAddressUtils;
  14.  
  15. import android.content.Context;
  16. import android.net.ConnectivityManager;
  17. import android.net.NetworkInfo;
  18. import android.net.wifi.WifiInfo;
  19. import android.net.wifi.WifiManager;
  20. import android.telephony.TelephonyManager;
  21. import android.text.TextUtils;
  22.  
  23. /**
  24. * 工具类
  25. *
  26. * @author weijiang204321
  27. *
  28. */
  29. public class Utils {
  30.  
  31. public static Context mContext;
  32.  
  33. public static void init(Context context) {
  34. mContext = context;
  35. }
  36.  
  37. /**
  38. *
  39. * @param str
  40. * @return 字符串是否为空
  41. */
  42. public static boolean isNotEmpty(String str) {
  43. if (str != null && !"".equals(str)) {
  44. return true;
  45. }
  46. return false;
  47. }
  48.  
  49. /**
  50. * 获取手机的Mac地址
  51. *
  52. * @return
  53. */
  54. public static String getMacAddress() {
  55. String result = "";
  56. try {
  57. WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
  58. WifiInfo wifiInfo = wifiManager.getConnectionInfo();
  59. result = wifiInfo.getMacAddress();
  60. } catch (Exception e) {
  61. result = "";
  62. }
  63. return result;
  64. }
  65.  
  66. /**
  67. * 获取手机的imei
  68. *
  69. * @return
  70. */
  71. public static String getImeiInfo() {
  72. try {
  73. TelephonyManager mTm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
  74. return mTm.getDeviceId();
  75. } catch (Exception e) {
  76. e.printStackTrace();
  77. return "";
  78. }
  79.  
  80. }
  81.  
  82. /**
  83. * 获取手机的imsi
  84. *
  85. * @return
  86. */
  87. public static String getImsiInfo() {
  88. try {
  89. String imsi = "";
  90. TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
  91. if (telephonyManager != null) {
  92. imsi = telephonyManager.getSubscriberId();
  93. }
  94. if (TextUtils.isEmpty(imsi)) {
  95. imsi = "UNKNOWN";
  96. }
  97. return imsi;
  98. } catch (Exception e) {
  99. return "";
  100. }
  101. }
  102.  
  103. /**
  104. * 获取手机型号
  105. *
  106. * @return
  107. */
  108. public static String getTypeInfo() {
  109. return android.os.Build.MODEL; // 手机型号
  110. }
  111.  
  112. /**
  113. * 获取手机系统版本
  114. *
  115. * @return
  116. */
  117. public static String getOsVersion() {
  118. return android.os.Build.VERSION.RELEASE;
  119. }
  120.  
  121. /**
  122. * 获取路由器的SSID
  123. *
  124. * @return
  125. */
  126. public static String getRouteSSID() {
  127. try {
  128. WifiManager wm = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
  129. WifiInfo info = wm.getConnectionInfo();
  130. if(info.getSSID().contains("<")){
  131. return "";
  132. }else{
  133. return info.getSSID().replace("\"","") + "";
  134. }
  135. } catch (Exception e) {
  136. AppListYPLog.e("异常:" + e.getMessage() + ",获取SSID失败!");
  137. return "";
  138. }
  139. }
  140.  
  141. /**
  142. * 获取路由器的Mac地址
  143. *
  144. * @return
  145. */
  146. public static String getRouteMac() {
  147. try {
  148. WifiManager wm = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
  149. WifiInfo info = wm.getConnectionInfo();
  150. if(info.getBSSID() == null){
  151. return "";
  152. }else{
  153. return info.getBSSID() + "";
  154. }
  155. } catch (Exception e) {
  156. AppListYPLog.e("异常:" + e.getMessage() + ",获取Mac地址失败!");
  157. return "";
  158. }
  159. }
  160.  
  161. /**
  162. * 解析uri参数
  163. * @param uri
  164. * @return
  165. */
  166. public static Map<String,String> getParam(String uri){
  167. Map<String,String> params = new HashMap<String,String>();
  168. try{
  169. if(isNotEmpty(uri)){
  170. String subStr = uri.substring(uri.indexOf("?")+1);
  171. String[] ary = subStr.split("&");
  172. for(int i=0;i<ary.length;i++){
  173. String[] temp = ary[i].split("=");
  174. if(temp.length<2){
  175. params.put(temp[0], "");
  176. }else{
  177. params.put(temp[0], temp[1]);
  178. }
  179.  
  180. }
  181. return params;
  182. }else{
  183. return null;
  184. }
  185. }catch(Exception e){
  186. return null;
  187. }
  188.  
  189. }
  190.  
  191. /**
  192. * 判断网络
  193. * @param ctx
  194. * @return
  195. */
  196. public static boolean checkNetWorkState() {
  197. boolean isnetwork = false;
  198. ConnectivityManager connManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
  199. NetworkInfo info = connManager.getActiveNetworkInfo();
  200.  
  201. if (info != null && (info.isAvailable() || info.isConnected())) {
  202. isnetwork = true;
  203. }
  204. return isnetwork;
  205. }
  206.  
  207. /**
  208. * 获取本机的ip
  209. * @return
  210. */
  211. public static String getLocalHostIp(){
  212. String ipaddress = "";
  213. try{
  214. Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
  215. // 遍历所用的网络接口
  216. while (en.hasMoreElements()){
  217. NetworkInterface nif = en.nextElement();// 得到每一个网络接口绑定的所有ip
  218. Enumeration<InetAddress> inet = nif.getInetAddresses();
  219. // 遍历每一个接口绑定的所有ip
  220. while (inet.hasMoreElements()){
  221. InetAddress ip = inet.nextElement();
  222. if (!ip.isLoopbackAddress()&& InetAddressUtils.isIPv4Address(ip.getHostAddress())){
  223. return ip.getHostAddress();
  224. }
  225. }
  226. }
  227. }catch (SocketException e){
  228. AppListYPLog.e("feige", "获取本地ip地址失败");
  229. }
  230. return ipaddress;
  231. }
  232.  
  233. /**
  234. * 检查端口port是否被占用了
  235. * @param port
  236. * @return
  237. */
  238. public static boolean checkPort(int port){
  239. try{
  240. InetAddress theAddress=InetAddress.getByName("127.0.0.1");
  241. try {
  242. Socket theSocket = new Socket(theAddress,port);
  243. theSocket.close();
  244. theSocket = null;
  245. theAddress = null;
  246. return false;
  247. }catch (IOException e) {
  248. AppListYPLog.e("异常:"+e.getMessage()+"检查端口号是否被占用");
  249. }catch(Exception e){
  250. AppListYPLog.e("异常:"+e.getMessage()+"检查端口号是否被占用");
  251. }
  252. }catch(UnknownHostException e) {
  253. AppListYPLog.e("异常:"+e.getMessage()+"检查端口号是否被占用");
  254. }
  255. return true;
  256. }
  257.  
  258. }

网络工具类NetUtils

  1. package com.sohu.tests;
  2.  
  3. import java.io.IOException;
  4. import java.util.ArrayList;
  5. import java.util.HashMap;
  6. import java.util.Iterator;
  7. import java.util.List;
  8. import java.util.Map.Entry;
  9. import java.util.Set;
  10.  
  11. import org.apache.http.HttpResponse;
  12. import org.apache.http.NameValuePair;
  13. import org.apache.http.client.ClientProtocolException;
  14. import org.apache.http.client.HttpClient;
  15. import org.apache.http.client.entity.UrlEncodedFormEntity;
  16. import org.apache.http.client.methods.HttpGet;
  17. import org.apache.http.client.methods.HttpPost;
  18. import org.apache.http.impl.client.DefaultHttpClient;
  19. import org.apache.http.message.BasicNameValuePair;
  20. import org.apache.http.params.CoreConnectionPNames;
  21. import org.apache.http.params.HttpConnectionParams;
  22. import org.apache.http.params.HttpParams;
  23. import org.apache.http.protocol.HTTP;
  24. import org.apache.http.util.EntityUtils;
  25.  
  26. public final class NetUtils {
  27.  
  28. /**
  29. * 上传数据
  30. *
  31. * @param url
  32. * @param param
  33. * @return
  34. */
  35. public static String postData(String url, HashMap<String, String> param) {
  36.  
  37. HttpPost httpPost = new HttpPost(url);
  38. // 设置HTTP POST请求参数必须用NameValuePair对象
  39. List<NameValuePair> params = new ArrayList<NameValuePair>();
  40. if (param != null) {
  41. Set<Entry<String, String>> set = param.entrySet();
  42. Iterator<Entry<String, String>> iterator = set.iterator();
  43. while (iterator.hasNext()) {
  44. Entry<String, String> tempEntry = iterator.next();
  45. params.add(new BasicNameValuePair(tempEntry.getKey(), tempEntry.getValue()));
  46. }
  47. } else {
  48. AppListYPLog.e("DEMO:", "上传参数错误");
  49. return null;
  50. }
  51. HttpResponse httpResponse = null;
  52. try {
  53. // 设置httpPost请求参数
  54. httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
  55. HttpClient httpClient = new DefaultHttpClient();
  56. // 请求超时
  57. httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
  58. // 读取超时
  59. httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000);
  60. httpResponse = httpClient.execute(httpPost);
  61. if (httpResponse.getStatusLine().getStatusCode() == 200) {
  62. // 第三步,使用getEntity方法活得返回结果
  63. String result = EntityUtils.toString(httpResponse.getEntity());
  64. return result;
  65. }
  66. } catch (ClientProtocolException e) {
  67. AppListYPLog.e("异常:" + e.getMessage());
  68. return null;
  69. } catch (IOException e) {
  70. AppListYPLog.e("异常:" + e.getMessage());
  71. return null;
  72. }
  73. return null;
  74. }
  75.  
  76. /**
  77. * @return 通过Request方式曝光
  78. */
  79. public static boolean uploadRequest(String baseUrl, String param) throws ClientProtocolException, IOException {
  80. HttpGet httpGet = null;
  81. if (param != null && !"".equals(param)) {
  82. httpGet = new HttpGet(baseUrl + "?" + param);
  83. } else {
  84. httpGet = new HttpGet(baseUrl);
  85. }
  86. AppListYPLog.e("URL:"+httpGet.getURI()+"");
  87. HttpParams params = httpGet.getParams();
  88. HttpConnectionParams.setConnectionTimeout(params, 3000);
  89. HttpConnectionParams.setSoTimeout(params, 3000);
  90. HttpClient httpClient = new DefaultHttpClient(params);
  91. HttpResponse response = httpClient.execute(httpGet);
  92. int statusCode = response.getStatusLine().getStatusCode();
  93. AppListYPLog.e("响应码:" + statusCode);
  94. if (statusCode < 300 && statusCode >= 200) {
  95. return true;
  96. }
  97. return false;
  98. }
  99.  
  100. }

常量类:

  1. package com.sohu.tests;
  2.  
  3. /**
  4. * 常量类
  5. * @author weijiang204321
  6. *
  7. */
  8. public class Consts {
  9.  
  10. /*cookie等信息上传url*/
  11. public static final String cookieUrl = "http://192.168.1.110:8080/HttpServer/FinishServlets";
  12.  
  13. /*注册的url*/
  14. public static final String registerUrl = "http://192.168.1.110:8080/HttpServer/RegisterServlets";
  15.  
  16. /*备用端口*/
  17. public static int[] portAry = new int[]{23021,10034,48990};
  18.  
  19. /*默认端口*/
  20. public static int defaultPort = 23021;
  21.  
  22. }

打印Log类

  1. package com.sohu.tests;
  2.  
  3. import android.util.Log;
  4.  
  5. /**
  6. * 打印Log信息
  7. * @author weijiang204321
  8. *
  9. */
  10. public class AppListYPLog {
  11.  
  12. private final static String TAG = "APPLIST";
  13. private static boolean SHOW_LOG = true;
  14.  
  15. private AppListYPLog() {
  16. }
  17.  
  18. public static void closeLog() {
  19. SHOW_LOG = false;
  20. }
  21.  
  22. public static void i(String msg) {
  23. if (SHOW_LOG) {
  24. Log.i(TAG, msg);
  25. }
  26. }
  27.  
  28. public static void d(String msg) {
  29. if (SHOW_LOG) {
  30. Log.d(TAG, msg);
  31. }
  32. }
  33.  
  34. public static void w(Exception ex) {
  35. if (SHOW_LOG) {
  36. ex.printStackTrace();
  37. }
  38. }
  39.  
  40. public static void e(String msg) {
  41. if (SHOW_LOG) {
  42. Log.e(TAG, msg);
  43. }
  44. }
  45.  
  46. public static void i(String tag, String msg) {
  47. if (SHOW_LOG) {
  48. Log.i(tag, msg);
  49. }
  50. }
  51.  
  52. public static void d(String tag, String msg) {
  53. if (SHOW_LOG) {
  54. Log.d(tag, msg);
  55. }
  56. }
  57.  
  58. public static void w(String tag, String msg) {
  59. if (SHOW_LOG) {
  60. Log.w(tag, msg);
  61. }
  62. }
  63.  
  64. public static void e(String tag, String msg) {
  65. if (SHOW_LOG) {
  66. Log.e(tag, msg);
  67. }
  68. }
  69.  
  70. }

测试的Demo:

  1. package com.sohu.tests;
  2.  
  3. import android.app.Activity;
  4. import android.content.Intent;
  5. import android.os.Bundle;
  6.  
  7. public class Main extends Activity {
  8.  
  9. @Override
  10. protected void onCreate(Bundle savedInstanceState) {
  11. super.onCreate(savedInstanceState);
  12. setContentView(R.layout.mainlay);
  13. startService(new Intent(this, SocketService.class));
  14. }
  15.  
  16. }

手机端的HttpServer就搭建完成了,下面我们要想测试的话,就必须在搭建一个Server端,我们这里就简单的建立一个Servlet:

移动端进行注册的接口:

  1. package com.weijiang.httpserver;
  2.  
  3. import java.io.IOException;
  4. import java.util.Date;
  5.  
  6. import javax.servlet.ServletException;
  7. import javax.servlet.http.HttpServlet;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10.  
  11. public class RegisterServlets extends HttpServlet {
  12.  
  13. private static final long serialVersionUID = 1L;
  14.  
  15. protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
  16. System.out.println("imei:"+req.getParameter("imei"));
  17. System.out.println("hs_ip:"+req.getParameter("hs_ip"));
  18. System.out.println("route_mac:"+req.getParameter("route_mac"));
  19. System.out.println("route_ssid:"+req.getParameter("route_ssid"));
  20. System.out.println("timetag:"+new Date(Long.parseLong(req.getParameter("timetag"))));
  21. }
  22.  
  23. protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
  24. doGet(req,resp);
  25. }
  26.  
  27. }

移动端完成操作的接口:

  1. package com.weijiang.httpserver;
  2.  
  3. import java.io.IOException;
  4. import java.util.Date;
  5.  
  6. import javax.servlet.ServletException;
  7. import javax.servlet.http.HttpServlet;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10.  
  11. public class FinishServlets extends HttpServlet {
  12.  
  13. private static final long serialVersionUID = 1L;
  14.  
  15. protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
  16. System.out.println("cookie:"+req.getParameter("cookie"));
  17. System.out.println("imei:"+req.getParameter("imei"));
  18. System.out.println("visitor_ip:"+req.getParameter("visitor_ip"));
  19. System.out.println("local_ip:"+req.getParameter("local_ip"));
  20. System.out.println("route_mac:"+req.getParameter("route_mac"));
  21. System.out.println("route_ssid:"+req.getParameter("route_ssid"));
  22. System.out.println("timetag:"+new Date(Long.parseLong(req.getParameter("timetag"))));
  23. }
  24.  
  25. protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
  26. doGet(req,resp);
  27. }
  28.  
  29. }

模拟携带有cookie值的Html页面

  1. <body>
  2. <a href='http://192.168.1.109:23021?cookie=123456'>Click</a>
  3. </body>

这里就是为了简单的模拟,所以直接随便写了一个cookie值

我们将PC和手机进行联网,这里不需要连接在一个网段中,只要在一个公网内就可以了,即他们两个可以ping通就可以,我这里在家里面测试的,用的是自己的路由器,所以一定是在一个网段中,我们查看PC的ip地址:

手机端的ip地址:

这样我们下面就可以来进行测试了,首先我们将Android应用部署到手机中,同时我们将Server启动,测试流程很简单:我们尝试改变网络状态,将网路断开,在进行连接,打印Log如下:

这里我们看到注册成功了,而且将手机的HttpServer的ip地址和监听端口上报了

我们在Server查看上报的信息:

我们就可以将手机的的内网地址进行保存,这里我们要注意在前面我们说到,这里还有一个步骤就是要获取公网的ip地址

上面的注册流程就走通了,下面我们看一下,完成操作的测试:

我们在浏览器中访问:

http://localhost:8080/HttpServer/index.jsp

点击Click,我们看到控制台中Log信息

我们看到完成操作,将cookie值和imei上报给Server端了,同时记录了来访者的ip地址

我们在Server的控制台中看到打印信息:

这样我们就将手机的imei和html页面的cookie值进行绑定了。。

前面我们说到了搭建移动端的Server的时候还有一种方法就是使用一个老外写的一个简单的类:

NanoHTTPD:

  1. package com.sohu.nanohttpd;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.ByteArrayInputStream;
  5. import java.io.Closeable;
  6. import java.io.File;
  7. import java.io.FileInputStream;
  8. import java.io.FileOutputStream;
  9. import java.io.IOException;
  10. import java.io.InputStream;
  11. import java.io.InputStreamReader;
  12. import java.io.OutputStream;
  13. import java.io.PrintWriter;
  14. import java.io.RandomAccessFile;
  15. import java.io.PushbackInputStream;
  16. import java.io.UnsupportedEncodingException;
  17. import java.net.InetAddress;
  18. import java.net.InetSocketAddress;
  19. import java.net.ServerSocket;
  20. import java.net.Socket;
  21. import java.net.SocketException;
  22. import java.net.SocketTimeoutException;
  23. import java.net.URLDecoder;
  24. import java.nio.ByteBuffer;
  25. import java.nio.channels.FileChannel;
  26. import java.text.SimpleDateFormat;
  27. import java.util.ArrayList;
  28. import java.util.Calendar;
  29. import java.util.Date;
  30. import java.util.HashMap;
  31. import java.util.HashSet;
  32. import java.util.Iterator;
  33. import java.util.List;
  34. import java.util.Locale;
  35. import java.util.Map;
  36. import java.util.Set;
  37. import java.util.StringTokenizer;
  38. import java.util.TimeZone;
  39.  
  40. /**
  41. * A simple, tiny, nicely embeddable HTTP server in Java
  42. * <p/>
  43. * <p/>
  44. * NanoHTTPD
  45. * <p></p>Copyright (c) 2012-2013 by Paul S. Hawke, 2001,2005-2013 by Jarno Elonen, 2010 by Konstantinos Togias</p>
  46. * <p/>
  47. * <p/>
  48. * <b>Features + limitations: </b>
  49. * <ul>
  50. * <p/>
  51. * <li>Only one Java file</li>
  52. * <li>Java 5 compatible</li>
  53. * <li>Released as open source, Modified BSD licence</li>
  54. * <li>No fixed config files, logging, authorization etc. (Implement yourself if you need them.)</li>
  55. * <li>Supports parameter parsing of GET and POST methods (+ rudimentary PUT support in 1.25)</li>
  56. * <li>Supports both dynamic content and file serving</li>
  57. * <li>Supports file upload (since version 1.2, 2010)</li>
  58. * <li>Supports partial content (streaming)</li>
  59. * <li>Supports ETags</li>
  60. * <li>Never caches anything</li>
  61. * <li>Doesn't limit bandwidth, request time or simultaneous connections</li>
  62. * <li>Default code serves files and shows all HTTP parameters and headers</li>
  63. * <li>File server supports directory listing, index.html and index.htm</li>
  64. * <li>File server supports partial content (streaming)</li>
  65. * <li>File server supports ETags</li>
  66. * <li>File server does the 301 redirection trick for directories without '/'</li>
  67. * <li>File server supports simple skipping for files (continue download)</li>
  68. * <li>File server serves also very long files without memory overhead</li>
  69. * <li>Contains a built-in list of most common mime types</li>
  70. * <li>All header names are converted lowercase so they don't vary between browsers/clients</li>
  71. * <p/>
  72. * </ul>
  73. * <p/>
  74. * <p/>
  75. * <b>How to use: </b>
  76. * <ul>
  77. * <p/>
  78. * <li>Subclass and implement serve() and embed to your own program</li>
  79. * <p/>
  80. * </ul>
  81. * <p/>
  82. * See the separate "LICENSE.md" file for the distribution license (Modified BSD licence)
  83. */
  84. public abstract class NanoHTTPD {
  85. /**
  86. * Maximum time to wait on Socket.getInputStream().read() (in milliseconds)
  87. * This is required as the Keep-Alive HTTP connections would otherwise
  88. * block the socket reading thread forever (or as long the browser is open).
  89. */
  90. public static final int SOCKET_READ_TIMEOUT = 5000;
  91. /**
  92. * Common mime type for dynamic content: plain text
  93. */
  94. public static final String MIME_PLAINTEXT = "text/plain";
  95. /**
  96. * Common mime type for dynamic content: html
  97. */
  98. public static final String MIME_HTML = "text/html";
  99. /**
  100. * Pseudo-Parameter to use to store the actual query string in the parameters map for later re-processing.
  101. */
  102. private static final String QUERY_STRING_PARAMETER = "NanoHttpd.QUERY_STRING";
  103. private final String hostname;
  104. private final int myPort;
  105. private ServerSocket myServerSocket;
  106. private Set<Socket> openConnections = new HashSet<Socket>();
  107. private Thread myThread;
  108. /**
  109. * Pluggable strategy for asynchronously executing requests.
  110. */
  111. private AsyncRunner asyncRunner;
  112. /**
  113. * Pluggable strategy for creating and cleaning up temporary files.
  114. */
  115. private TempFileManagerFactory tempFileManagerFactory;
  116.  
  117. /**
  118. * Constructs an HTTP server on given port.
  119. */
  120. public NanoHTTPD(int port) {
  121. this(null, port);
  122. }
  123.  
  124. /**
  125. * Constructs an HTTP server on given hostname and port.
  126. */
  127. public NanoHTTPD(String hostname, int port) {
  128. this.hostname = hostname;
  129. this.myPort = port;
  130. setTempFileManagerFactory(new DefaultTempFileManagerFactory());
  131. setAsyncRunner(new DefaultAsyncRunner());
  132. }
  133.  
  134. private static final void safeClose(Closeable closeable) {
  135. if (closeable != null) {
  136. try {
  137. closeable.close();
  138. } catch (IOException e) {
  139. }
  140. }
  141. }
  142.  
  143. private static final void safeClose(Socket closeable) {
  144. if (closeable != null) {
  145. try {
  146. closeable.close();
  147. } catch (IOException e) {
  148. }
  149. }
  150. }
  151.  
  152. private static final void safeClose(ServerSocket closeable) {
  153. if (closeable != null) {
  154. try {
  155. closeable.close();
  156. } catch (IOException e) {
  157. }
  158. }
  159. }
  160.  
  161. /**
  162. * Start the server.
  163. *
  164. * @throws IOException if the socket is in use.
  165. */
  166. public void start() throws IOException {
  167. myServerSocket = new ServerSocket();
  168. myServerSocket.bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));
  169.  
  170. myThread = new Thread(new Runnable() {
  171. @Override
  172. public void run() {
  173. do {
  174. try {
  175. final Socket finalAccept = myServerSocket.accept();
  176. registerConnection(finalAccept);
  177. finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
  178. final InputStream inputStream = finalAccept.getInputStream();
  179. asyncRunner.exec(new Runnable() {
  180. @Override
  181. public void run() {
  182. OutputStream outputStream = null;
  183. try {
  184. outputStream = finalAccept.getOutputStream();
  185. TempFileManager tempFileManager = tempFileManagerFactory.create();
  186. HTTPSession session = new HTTPSession(tempFileManager, inputStream, outputStream, finalAccept.getInetAddress());
  187. while (!finalAccept.isClosed()) {
  188. session.execute();
  189. }
  190. } catch (Exception e) {
  191. // When the socket is closed by the client, we throw our own SocketException
  192. // to break the "keep alive" loop above.
  193. if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) {
  194. e.printStackTrace();
  195. }
  196. } finally {
  197. safeClose(outputStream);
  198. safeClose(inputStream);
  199. safeClose(finalAccept);
  200. unRegisterConnection(finalAccept);
  201. }
  202. }
  203. });
  204. } catch (IOException e) {
  205. }
  206. } while (!myServerSocket.isClosed());
  207. }
  208. });
  209. myThread.setDaemon(true);
  210. myThread.setName("NanoHttpd Main Listener");
  211. myThread.start();
  212. }
  213.  
  214. /**
  215. * Stop the server.
  216. */
  217. public void stop() {
  218. try {
  219. safeClose(myServerSocket);
  220. closeAllConnections();
  221. myThread.join();
  222. } catch (Exception e) {
  223. e.printStackTrace();
  224. }
  225. }
  226.  
  227. /**
  228. * Registers that a new connection has been set up.
  229. *
  230. * @param socket
  231. * the {@link Socket} for the connection.
  232. */
  233. public synchronized void registerConnection(Socket socket) {
  234. openConnections.add(socket);
  235. }
  236.  
  237. /**
  238. * Registers that a connection has been closed
  239. *
  240. * @param socket
  241. * the {@link Socket} for the connection.
  242. */
  243. public synchronized void unRegisterConnection(Socket socket) {
  244. openConnections.remove(socket);
  245. }
  246.  
  247. /**
  248. * Forcibly closes all connections that are open.
  249. */
  250. public synchronized void closeAllConnections() {
  251. for (Socket socket : openConnections) {
  252. safeClose(socket);
  253. }
  254. }
  255.  
  256. public final int getListeningPort() {
  257. return myServerSocket == null ? -1 : myServerSocket.getLocalPort();
  258. }
  259.  
  260. public final boolean wasStarted() {
  261. return myServerSocket != null && myThread != null;
  262. }
  263.  
  264. public final boolean isAlive() {
  265. return wasStarted() && !myServerSocket.isClosed() && myThread.isAlive();
  266. }
  267.  
  268. /**
  269. * Override this to customize the server.
  270. * <p/>
  271. * <p/>
  272. * (By default, this delegates to serveFile() and allows directory listing.)
  273. *
  274. * @param uri Percent-decoded URI without parameters, for example "/index.cgi"
  275. * @param method "GET", "POST" etc.
  276. * @param parms Parsed, percent decoded parameters from URI and, in case of POST, data.
  277. * @param headers Header entries, percent decoded
  278. * @return HTTP response, see class Response for details
  279. */
  280. @Deprecated
  281. public Response serve(String uri, Method method, Map<String, String> headers, Map<String, String> parms,
  282. Map<String, String> files) {
  283. return new Response(Response.Status.NOT_FOUND, MIME_PLAINTEXT, "Not Found");
  284. }
  285.  
  286. /**
  287. * Override this to customize the server.
  288. * <p/>
  289. * <p/>
  290. * (By default, this delegates to serveFile() and allows directory listing.)
  291. *
  292. * @param session The HTTP session
  293. * @return HTTP response, see class Response for details
  294. * 我们需要自己实现这个方法
  295. */
  296. public Response serve(IHTTPSession session) {
  297. Map<String, String> files = new HashMap<String, String>();
  298. Method method = session.getMethod();
  299. if (Method.PUT.equals(method) || Method.POST.equals(method)) {
  300. try {
  301. session.parseBody(files);
  302. } catch (IOException ioe) {
  303. return new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
  304. } catch (ResponseException re) {
  305. return new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage());
  306. }
  307. }
  308.  
  309. Map<String, String> parms = session.getParms();
  310. parms.put(QUERY_STRING_PARAMETER, session.getQueryParameterString());
  311. return serve(session.getUri(), method, session.getHeaders(), parms, files);
  312. }
  313.  
  314. /**
  315. * Decode percent encoded <code>String</code> values.
  316. *
  317. * @param str the percent encoded <code>String</code>
  318. * @return expanded form of the input, for example "foo%20bar" becomes "foo bar"
  319. */
  320. protected String decodePercent(String str) {
  321. String decoded = null;
  322. try {
  323. decoded = URLDecoder.decode(str, "UTF8");
  324. } catch (UnsupportedEncodingException ignored) {
  325. }
  326. return decoded;
  327. }
  328.  
  329. /**
  330. * Decode parameters from a URL, handing the case where a single parameter name might have been
  331. * supplied several times, by return lists of values. In general these lists will contain a single
  332. * element.
  333. *
  334. * @param parms original <b>NanoHttpd</b> parameters values, as passed to the <code>serve()</code> method.
  335. * @return a map of <code>String</code> (parameter name) to <code>List<String></code> (a list of the values supplied).
  336. */
  337. protected Map<String, List<String>> decodeParameters(Map<String, String> parms) {
  338. return this.decodeParameters(parms.get(QUERY_STRING_PARAMETER));
  339. }
  340.  
  341. /**
  342. * Decode parameters from a URL, handing the case where a single parameter name might have been
  343. * supplied several times, by return lists of values. In general these lists will contain a single
  344. * element.
  345. *
  346. * @param queryString a query string pulled from the URL.
  347. * @return a map of <code>String</code> (parameter name) to <code>List<String></code> (a list of the values supplied).
  348. */
  349. protected Map<String, List<String>> decodeParameters(String queryString) {
  350. Map<String, List<String>> parms = new HashMap<String, List<String>>();
  351. if (queryString != null) {
  352. StringTokenizer st = new StringTokenizer(queryString, "&");
  353. while (st.hasMoreTokens()) {
  354. String e = st.nextToken();
  355. int sep = e.indexOf('=');
  356. String propertyName = (sep >= 0) ? decodePercent(e.substring(0, sep)).trim() : decodePercent(e).trim();
  357. if (!parms.containsKey(propertyName)) {
  358. parms.put(propertyName, new ArrayList<String>());
  359. }
  360. String propertyValue = (sep >= 0) ? decodePercent(e.substring(sep + 1)) : null;
  361. if (propertyValue != null) {
  362. parms.get(propertyName).add(propertyValue);
  363. }
  364. }
  365. }
  366. return parms;
  367. }
  368.  
  369. // ------------------------------------------------------------------------------- //
  370. //
  371. // Threading Strategy.
  372. //
  373. // ------------------------------------------------------------------------------- //
  374.  
  375. /**
  376. * Pluggable strategy for asynchronously executing requests.
  377. *
  378. * @param asyncRunner new strategy for handling threads.
  379. */
  380. public void setAsyncRunner(AsyncRunner asyncRunner) {
  381. this.asyncRunner = asyncRunner;
  382. }
  383.  
  384. // ------------------------------------------------------------------------------- //
  385. //
  386. // Temp file handling strategy.
  387. //
  388. // ------------------------------------------------------------------------------- //
  389.  
  390. /**
  391. * Pluggable strategy for creating and cleaning up temporary files.
  392. *
  393. * @param tempFileManagerFactory new strategy for handling temp files.
  394. */
  395. public void setTempFileManagerFactory(TempFileManagerFactory tempFileManagerFactory) {
  396. this.tempFileManagerFactory = tempFileManagerFactory;
  397. }
  398.  
  399. /**
  400. * HTTP Request methods, with the ability to decode a <code>String</code> back to its enum value.
  401. */
  402. public enum Method {
  403. GET, PUT, POST, DELETE, HEAD, OPTIONS;
  404.  
  405. static Method lookup(String method) {
  406. for (Method m : Method.values()) {
  407. if (m.toString().equalsIgnoreCase(method)) {
  408. return m;
  409. }
  410. }
  411. return null;
  412. }
  413. }
  414.  
  415. /**
  416. * Pluggable strategy for asynchronously executing requests.
  417. */
  418. public interface AsyncRunner {
  419. void exec(Runnable code);
  420. }
  421.  
  422. /**
  423. * Factory to create temp file managers.
  424. */
  425. public interface TempFileManagerFactory {
  426. TempFileManager create();
  427. }
  428.  
  429. // ------------------------------------------------------------------------------- //
  430.  
  431. /**
  432. * Temp file manager.
  433. * <p/>
  434. * <p>Temp file managers are created 1-to-1 with incoming requests, to create and cleanup
  435. * temporary files created as a result of handling the request.</p>
  436. */
  437. public interface TempFileManager {
  438. TempFile createTempFile() throws Exception;
  439.  
  440. void clear();
  441. }
  442.  
  443. /**
  444. * A temp file.
  445. * <p/>
  446. * <p>Temp files are responsible for managing the actual temporary storage and cleaning
  447. * themselves up when no longer needed.</p>
  448. */
  449. public interface TempFile {
  450. OutputStream open() throws Exception;
  451.  
  452. void delete() throws Exception;
  453.  
  454. String getName();
  455. }
  456.  
  457. /**
  458. * Default threading strategy for NanoHttpd.
  459. * <p/>
  460. * <p>By default, the server spawns a new Thread for every incoming request. These are set
  461. * to <i>daemon</i> status, and named according to the request number. The name is
  462. * useful when profiling the application.</p>
  463. */
  464. public static class DefaultAsyncRunner implements AsyncRunner {
  465. private long requestCount;
  466.  
  467. @Override
  468. public void exec(Runnable code) {
  469. ++requestCount;
  470. Thread t = new Thread(code);
  471. t.setDaemon(true);
  472. t.setName("NanoHttpd Request Processor (#" + requestCount + ")");
  473. t.start();
  474. }
  475. }
  476.  
  477. /**
  478. * Default strategy for creating and cleaning up temporary files.
  479. * <p/>
  480. * <p></p>This class stores its files in the standard location (that is,
  481. * wherever <code>java.io.tmpdir</code> points to). Files are added
  482. * to an internal list, and deleted when no longer needed (that is,
  483. * when <code>clear()</code> is invoked at the end of processing a
  484. * request).</p>
  485. */
  486. public static class DefaultTempFileManager implements TempFileManager {
  487. private final String tmpdir;
  488. private final List<TempFile> tempFiles;
  489.  
  490. public DefaultTempFileManager() {
  491. tmpdir = System.getProperty("java.io.tmpdir");
  492. tempFiles = new ArrayList<TempFile>();
  493. }
  494.  
  495. @Override
  496. public TempFile createTempFile() throws Exception {
  497. DefaultTempFile tempFile = new DefaultTempFile(tmpdir);
  498. tempFiles.add(tempFile);
  499. return tempFile;
  500. }
  501.  
  502. @Override
  503. public void clear() {
  504. for (TempFile file : tempFiles) {
  505. try {
  506. file.delete();
  507. } catch (Exception ignored) {
  508. }
  509. }
  510. tempFiles.clear();
  511. }
  512. }
  513.  
  514. /**
  515. * Default strategy for creating and cleaning up temporary files.
  516. * <p/>
  517. * <p></p></[>By default, files are created by <code>File.createTempFile()</code> in
  518. * the directory specified.</p>
  519. */
  520. public static class DefaultTempFile implements TempFile {
  521. private File file;
  522. private OutputStream fstream;
  523.  
  524. public DefaultTempFile(String tempdir) throws IOException {
  525. file = File.createTempFile("NanoHTTPD-", "", new File(tempdir));
  526. fstream = new FileOutputStream(file);
  527. }
  528.  
  529. @Override
  530. public OutputStream open() throws Exception {
  531. return fstream;
  532. }
  533.  
  534. @Override
  535. public void delete() throws Exception {
  536. safeClose(fstream);
  537. file.delete();
  538. }
  539.  
  540. @Override
  541. public String getName() {
  542. return file.getAbsolutePath();
  543. }
  544. }
  545.  
  546. /**
  547. * HTTP response. Return one of these from serve().
  548. */
  549. public static class Response {
  550. /**
  551. * HTTP status code after processing, e.g. "200 OK", HTTP_OK
  552. */
  553. private Status status;
  554. /**
  555. * MIME type of content, e.g. "text/html"
  556. */
  557. private String mimeType;
  558. /**
  559. * Data of the response, may be null.
  560. */
  561. private InputStream data;
  562. /**
  563. * Headers for the HTTP response. Use addHeader() to add lines.
  564. */
  565. private Map<String, String> header = new HashMap<String, String>();
  566. /**
  567. * The request method that spawned this response.
  568. */
  569. private Method requestMethod;
  570. /**
  571. * Use chunkedTransfer
  572. */
  573. private boolean chunkedTransfer;
  574.  
  575. /**
  576. * Default constructor: response = HTTP_OK, mime = MIME_HTML and your supplied message
  577. */
  578. public Response(String msg) {
  579. this(Status.OK, MIME_HTML, msg);
  580. }
  581.  
  582. /**
  583. * Basic constructor.
  584. */
  585. public Response(Status status, String mimeType, InputStream data) {
  586. this.status = status;
  587. this.mimeType = mimeType;
  588. this.data = data;
  589. }
  590.  
  591. /**
  592. * Convenience method that makes an InputStream out of given text.
  593. */
  594. public Response(Status status, String mimeType, String txt) {
  595. this.status = status;
  596. this.mimeType = mimeType;
  597. try {
  598. this.data = txt != null ? new ByteArrayInputStream(txt.getBytes("UTF-8")) : null;
  599. } catch (java.io.UnsupportedEncodingException uee) {
  600. uee.printStackTrace();
  601. }
  602. }
  603.  
  604. /**
  605. * Adds given line to the header.
  606. */
  607. public void addHeader(String name, String value) {
  608. header.put(name, value);
  609. }
  610.  
  611. /**
  612. * Sends given response to the socket.
  613. */
  614. private void send(OutputStream outputStream) {
  615. String mime = mimeType;
  616. SimpleDateFormat gmtFrmt = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
  617. gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT"));
  618.  
  619. try {
  620. if (status == null) {
  621. throw new Error("sendResponse(): Status can't be null.");
  622. }
  623. PrintWriter pw = new PrintWriter(outputStream);
  624. pw.print("HTTP/1.1 " + status.getDescription() + " \r\n");
  625.  
  626. if (mime != null) {
  627. pw.print("Content-Type: " + mime + "\r\n");
  628. }
  629.  
  630. if (header == null || header.get("Date") == null) {
  631. pw.print("Date: " + gmtFrmt.format(new Date()) + "\r\n");
  632. }
  633.  
  634. if (header != null) {
  635. for (String key : header.keySet()) {
  636. String value = header.get(key);
  637. pw.print(key + ": " + value + "\r\n");
  638. }
  639. }
  640.  
  641. pw.print("Connection: keep-alive\r\n");
  642.  
  643. if (requestMethod != Method.HEAD && chunkedTransfer) {
  644. sendAsChunked(outputStream, pw);
  645. } else {
  646. sendAsFixedLength(outputStream, pw);
  647. }
  648. outputStream.flush();
  649. safeClose(data);
  650. } catch (IOException ioe) {
  651. // Couldn't write? No can do.
  652. }
  653. }
  654.  
  655. private void sendAsChunked(OutputStream outputStream, PrintWriter pw) throws IOException {
  656. pw.print("Transfer-Encoding: chunked\r\n");
  657. pw.print("\r\n");
  658. pw.flush();
  659. int BUFFER_SIZE = 16 * 1024;
  660. byte[] CRLF = "\r\n".getBytes();
  661. byte[] buff = new byte[BUFFER_SIZE];
  662. int read;
  663. while ((read = data.read(buff)) > 0) {
  664. outputStream.write(String.format("%x\r\n", read).getBytes());
  665. outputStream.write(buff, 0, read);
  666. outputStream.write(CRLF);
  667. }
  668. outputStream.write(String.format("0\r\n\r\n").getBytes());
  669. }
  670.  
  671. private void sendAsFixedLength(OutputStream outputStream, PrintWriter pw) throws IOException {
  672. int pending = data != null ? data.available() : 0; // This is to support partial sends, see serveFile()
  673. pw.print("Content-Length: "+pending+"\r\n");
  674.  
  675. pw.print("\r\n");
  676. pw.flush();
  677.  
  678. if (requestMethod != Method.HEAD && data != null) {
  679. int BUFFER_SIZE = 16 * 1024;
  680. byte[] buff = new byte[BUFFER_SIZE];
  681. while (pending > 0) {
  682. int read = data.read(buff, 0, ((pending > BUFFER_SIZE) ? BUFFER_SIZE : pending));
  683. if (read <= 0) {
  684. break;
  685. }
  686. outputStream.write(buff, 0, read);
  687.  
  688. pending -= read;
  689. }
  690. }
  691. }
  692.  
  693. public Status getStatus() {
  694. return status;
  695. }
  696.  
  697. public void setStatus(Status status) {
  698. this.status = status;
  699. }
  700.  
  701. public String getMimeType() {
  702. return mimeType;
  703. }
  704.  
  705. public void setMimeType(String mimeType) {
  706. this.mimeType = mimeType;
  707. }
  708.  
  709. public InputStream getData() {
  710. return data;
  711. }
  712.  
  713. public void setData(InputStream data) {
  714. this.data = data;
  715. }
  716.  
  717. public Method getRequestMethod() {
  718. return requestMethod;
  719. }
  720.  
  721. public void setRequestMethod(Method requestMethod) {
  722. this.requestMethod = requestMethod;
  723. }
  724.  
  725. public void setChunkedTransfer(boolean chunkedTransfer) {
  726. this.chunkedTransfer = chunkedTransfer;
  727. }
  728.  
  729. /**
  730. * Some HTTP response status codes
  731. */
  732. public enum Status {
  733. OK(200, "OK"), CREATED(201, "Created"), ACCEPTED(202, "Accepted"), NO_CONTENT(204, "No Content"), PARTIAL_CONTENT(206, "Partial Content"), REDIRECT(301,
  734. "Moved Permanently"), NOT_MODIFIED(304, "Not Modified"), BAD_REQUEST(400, "Bad Request"), UNAUTHORIZED(401,
  735. "Unauthorized"), FORBIDDEN(403, "Forbidden"), NOT_FOUND(404, "Not Found"), METHOD_NOT_ALLOWED(405, "Method Not Allowed"), RANGE_NOT_SATISFIABLE(416,
  736. "Requested Range Not Satisfiable"), INTERNAL_ERROR(500, "Internal Server Error");
  737. private final int requestStatus;
  738. private final String description;
  739.  
  740. Status(int requestStatus, String description) {
  741. this.requestStatus = requestStatus;
  742. this.description = description;
  743. }
  744.  
  745. public int getRequestStatus() {
  746. return this.requestStatus;
  747. }
  748.  
  749. public String getDescription() {
  750. return "" + this.requestStatus + " " + description;
  751. }
  752. }
  753. }
  754.  
  755. public static final class ResponseException extends Exception {
  756.  
  757. private final Response.Status status;
  758.  
  759. public ResponseException(Response.Status status, String message) {
  760. super(message);
  761. this.status = status;
  762. }
  763.  
  764. public ResponseException(Response.Status status, String message, Exception e) {
  765. super(message, e);
  766. this.status = status;
  767. }
  768.  
  769. public Response.Status getStatus() {
  770. return status;
  771. }
  772. }
  773.  
  774. /**
  775. * Default strategy for creating and cleaning up temporary files.
  776. */
  777. private class DefaultTempFileManagerFactory implements TempFileManagerFactory {
  778. @Override
  779. public TempFileManager create() {
  780. return new DefaultTempFileManager();
  781. }
  782. }
  783.  
  784. /**
  785. * Handles one session, i.e. parses the HTTP request and returns the response.
  786. */
  787. public interface IHTTPSession {
  788. void execute() throws IOException;
  789.  
  790. Map<String, String> getParms();
  791.  
  792. Map<String, String> getHeaders();
  793.  
  794. /**
  795. * @return the path part of the URL.
  796. */
  797. String getUri();
  798.  
  799. String getQueryParameterString();
  800.  
  801. Method getMethod();
  802.  
  803. InputStream getInputStream();
  804.  
  805. CookieHandler getCookies();
  806.  
  807. /**
  808. * Adds the files in the request body to the files map.
  809. * @arg files - map to modify
  810. */
  811. void parseBody(Map<String, String> files) throws IOException, ResponseException;
  812. }
  813.  
  814. protected class HTTPSession implements IHTTPSession {
  815. public static final int BUFSIZE = 8192;
  816. private final TempFileManager tempFileManager;
  817. private final OutputStream outputStream;
  818. private PushbackInputStream inputStream;
  819. private int splitbyte;
  820. private int rlen;
  821. private String uri;
  822. private Method method;
  823. private Map<String, String> parms;
  824. private Map<String, String> headers;
  825. private CookieHandler cookies;
  826. private String queryParameterString;
  827.  
  828. public HTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream) {
  829. this.tempFileManager = tempFileManager;
  830. this.inputStream = new PushbackInputStream(inputStream, BUFSIZE);
  831. this.outputStream = outputStream;
  832. }
  833.  
  834. public HTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream, InetAddress inetAddress) {
  835. this.tempFileManager = tempFileManager;
  836. this.inputStream = new PushbackInputStream(inputStream, BUFSIZE);
  837. this.outputStream = outputStream;
  838. String remoteIp = inetAddress.isLoopbackAddress() || inetAddress.isAnyLocalAddress() ? "127.0.0.1" : inetAddress.getHostAddress().toString();
  839. headers = new HashMap<String, String>();
  840.  
  841. headers.put("remote-addr", remoteIp);
  842. headers.put("http-client-ip", remoteIp);
  843. }
  844.  
  845. @Override
  846. public void execute() throws IOException {
  847. try {
  848. /* Read the first 8192 bytes.
  849. The full header should fit in here.
  850. Apache's default header limit is 8KB.
  851. Do NOT assume that a single read will get the entire header at once!
  852. header的最大长度为8192bytes,所以这里设置BUFSIZE为8192bytes
  853. */
  854. byte[] buf = new byte[BUFSIZE];
  855. splitbyte = 0;
  856. rlen = 0;//总共的长度
  857. {
  858. int read = -1;//每次读取的长度
  859. try {
  860. read = inputStream.read(buf, 0, BUFSIZE);
  861. } catch (Exception e) {
  862. safeClose(inputStream);
  863. safeClose(outputStream);
  864. throw new SocketException("NanoHttpd Shutdown");
  865. }
  866. if (read == -1) {
  867. // socket was been closed
  868. safeClose(inputStream);
  869. safeClose(outputStream);
  870. throw new SocketException("NanoHttpd Shutdown");
  871. }
  872. while (read > 0) {
  873. rlen += read;
  874. splitbyte = findHeaderEnd(buf, rlen);
  875. if (splitbyte > 0)//如果返回0则说明没有找到
  876. break;
  877. read = inputStream.read(buf, rlen, BUFSIZE - rlen);
  878. }
  879. }
  880. //如果读多了,则将多余的部分重新写到流里面
  881. if (splitbyte < rlen) {
  882. inputStream.unread(buf, splitbyte, rlen - splitbyte);
  883. }
  884.  
  885. parms = new HashMap<String, String>();
  886. if(null == headers) {
  887. headers = new HashMap<String, String>();
  888. }
  889.  
  890. // Create a BufferedReader for parsing the header.
  891. BufferedReader hin = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, rlen)));
  892.  
  893. // Decode the header into parms and header java properties
  894. Map<String, String> pre = new HashMap<String, String>();
  895. decodeHeader(hin, pre, parms, headers);
  896. /**
  897. * 取出客户端请求的方式:GET/POST
  898. */
  899. method = Method.lookup(pre.get("method"));
  900. if (method == null) {
  901. throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error.");
  902. }
  903. //请求的连接
  904. uri = pre.get("uri");
  905.  
  906. cookies = new CookieHandler(headers);
  907.  
  908. /*
  909. * Ok, now do the serve()
  910. * 解析
  911. */
  912. Response r = serve(this);
  913. if (r == null) {
  914. throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: Serve() returned a null response.");
  915. } else {
  916. cookies.unloadQueue(r);
  917. //响应客户端信息
  918. r.setRequestMethod(method);
  919. r.send(outputStream);
  920. }
  921. } catch (SocketException e) {
  922. // throw it out to close socket object (finalAccept)
  923. throw e;
  924. } catch (SocketTimeoutException ste) {
  925. throw ste;
  926. } catch (IOException ioe) {
  927. Response r = new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
  928. r.send(outputStream);
  929. safeClose(outputStream);
  930. } catch (ResponseException re) {
  931. Response r = new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage());
  932. r.send(outputStream);
  933. safeClose(outputStream);
  934. } finally {
  935. tempFileManager.clear();
  936. }
  937. }
  938.  
  939. @Override
  940. public void parseBody(Map<String, String> files) throws IOException, ResponseException {
  941. RandomAccessFile randomAccessFile = null;
  942. BufferedReader in = null;
  943. try {
  944. //创建临时文件
  945. randomAccessFile = getTmpBucket();
  946.  
  947. long size;
  948. if (headers.containsKey("content-length")) {
  949. size = Integer.parseInt(headers.get("content-length"));
  950. } else if (splitbyte < rlen) {
  951. size = rlen - splitbyte;
  952. } else {
  953. size = 0;
  954. }
  955.  
  956. /*
  957. * Now read all the body and write it to f
  958. * 将流的内容写到临时文件中
  959. */
  960. byte[] buf = new byte[512];
  961. while (rlen >= 0 && size > 0) {
  962. rlen = inputStream.read(buf, 0, (int)Math.min(size, 512));
  963. size -= rlen;
  964. if (rlen > 0) {
  965. randomAccessFile.write(buf, 0, rlen);
  966. }
  967. }
  968.  
  969. // Get the raw body as a byte []
  970. ByteBuffer fbuf = randomAccessFile.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, randomAccessFile.length());
  971. randomAccessFile.seek(0);//重新定位到临时文件的开始位置
  972.  
  973. // Create a BufferedReader for easily reading it as string.
  974. InputStream bin = new FileInputStream(randomAccessFile.getFD());
  975. in = new BufferedReader(new InputStreamReader(bin));
  976.  
  977. // If the method is POST, there may be parameters
  978. // in data section, too, read it:
  979. if (Method.POST.equals(method)) {
  980. String contentType = "";
  981. String contentTypeHeader = headers.get("content-type");
  982.  
  983. StringTokenizer st = null;
  984. if (contentTypeHeader != null) {
  985. st = new StringTokenizer(contentTypeHeader, ",; ");
  986. if (st.hasMoreTokens()) {
  987. contentType = st.nextToken();
  988. }
  989. }
  990. //表单提交,文件上传类型
  991. if ("multipart/form-data".equalsIgnoreCase(contentType)) {
  992. // Handle multipart/form-data
  993. if (!st.hasMoreTokens()) {
  994. throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but boundary missing. Usage: GET /example/file.html");
  995. }
  996.  
  997. String boundaryStartString = "boundary=";
  998. int boundaryContentStart = contentTypeHeader.indexOf(boundaryStartString) + boundaryStartString.length();
  999. String boundary = contentTypeHeader.substring(boundaryContentStart, contentTypeHeader.length());
  1000. if (boundary.startsWith("\"") && boundary.endsWith("\"")) {
  1001. boundary = boundary.substring(1, boundary.length() - 1);
  1002. }
  1003. //fbuf里面包含body的内容
  1004. decodeMultipartData(boundary, fbuf, in, parms, files);
  1005. } else {
  1006. // Handle application/x-www-form-urlencoded
  1007. String postLine = "";
  1008. StringBuilder postLineBuffer = new StringBuilder();
  1009. char pbuf[] = new char[512];
  1010. int read = in.read(pbuf);
  1011. while (read >= 0 && !postLine.endsWith("\r\n")) {
  1012. postLine = String.valueOf(pbuf, 0, read);
  1013. postLineBuffer.append(postLine);
  1014. read = in.read(pbuf);
  1015. }
  1016. postLine = postLineBuffer.toString().trim();
  1017. decodeParms(postLine, parms);
  1018. }
  1019. } else if (Method.PUT.equals(method)) {
  1020. String content = saveTmpFile(fbuf, 0, fbuf.limit());
  1021. files.put("content", content);
  1022. }
  1023. } finally {
  1024. safeClose(randomAccessFile);
  1025. safeClose(in);
  1026. }
  1027. }
  1028.  
  1029. /**
  1030. * Decodes the sent headers and loads the data into Key/value pairs
  1031. */
  1032. private void decodeHeader(BufferedReader in, Map<String, String> pre, Map<String, String> parms, Map<String, String> headers)
  1033. throws ResponseException {
  1034. try {
  1035. // Read the request line GET / HTTP/1.1
  1036. String inLine = in.readLine();
  1037. if (inLine == null) {
  1038. return;
  1039. }
  1040. //分隔inLine用 \t\n\r\f
  1041. StringTokenizer st = new StringTokenizer(inLine);
  1042. if (!st.hasMoreTokens()) {
  1043. throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error. Usage: GET /example/file.html");
  1044. }
  1045. String method = st.nextToken();
  1046. pre.put("method", method);
  1047. if (!st.hasMoreTokens()) {
  1048. throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Missing URI. Usage: GET /example/file.html");
  1049. }
  1050.  
  1051. String uri = st.nextToken();
  1052. /*
  1053. * Decode parameters from the URI
  1054. * 以"?" 来判断是否有参数
  1055. */
  1056. int qmi = uri.indexOf('?');
  1057. if (qmi >= 0) {//说明有参数,调用decodeParms将参数解析到parms中
  1058. decodeParms(uri.substring(qmi + 1), parms);
  1059. uri = decodePercent(uri.substring(0, qmi));
  1060. } else {
  1061. uri = decodePercent(uri);
  1062. }
  1063. // If there's another token, it's protocol version,
  1064. // followed by HTTP headers. Ignore version but parse headers.
  1065. // NOTE: this now forces header names lowercase since they are
  1066. // case insensitive and vary by client.
  1067. if (st.hasMoreTokens()) {
  1068. String line = in.readLine();
  1069. while (line != null && line.trim().length() > 0) {
  1070. int p = line.indexOf(':');
  1071. if (p >= 0)
  1072. headers.put(line.substring(0, p).trim().toLowerCase(Locale.US), line.substring(p + 1).trim());
  1073. line = in.readLine();
  1074. }
  1075. }
  1076. pre.put("uri", uri);
  1077. } catch (IOException ioe) {
  1078. throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe);
  1079. }
  1080. }
  1081.  
  1082. /**
  1083. * Decodes the Multipart Body data and put it into Key/Value pairs.
  1084. * @param boundary
  1085. * @param fbuf
  1086. * @param in
  1087. * @param parms header头里面的参数
  1088. * @param files 支持多文件上传功能
  1089. * @throws ResponseException
  1090. */
  1091. private void decodeMultipartData(String boundary, ByteBuffer fbuf, BufferedReader in, Map<String, String> parms,
  1092. Map<String, String> files) throws ResponseException {
  1093. try {
  1094. //根据boundary获取分割线与内容的间隔位置
  1095. int[] bpositions = getBoundaryPositions(fbuf, boundary.getBytes());
  1096. int boundarycount = 2;//源码为1,如果是上传单个文件会有问题
  1097. String mpline = in.readLine();
  1098. while (mpline != null) {
  1099. if (!mpline.contains(boundary)) {
  1100. throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but next chunk does not start with boundary. Usage: GET /example/file.html");
  1101. }
  1102. boundarycount++;
  1103. Map<String, String> item = new HashMap<String, String>();
  1104. mpline = in.readLine();
  1105. while (mpline != null && mpline.trim().length() > 0) {
  1106. int p = mpline.indexOf(':');
  1107. if (p != -1) {
  1108. item.put(mpline.substring(0, p).trim().toLowerCase(Locale.US), mpline.substring(p + 1).trim());
  1109. }
  1110. mpline = in.readLine();
  1111. }
  1112. if (mpline != null) {
  1113. String contentDisposition = item.get("content-disposition");
  1114. if (contentDisposition == null) {
  1115. throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but no content-disposition info found. Usage: GET /example/file.html");
  1116. }
  1117. StringTokenizer st = new StringTokenizer(contentDisposition, "; ");
  1118. Map<String, String> disposition = new HashMap<String, String>();
  1119. while (st.hasMoreTokens()) {
  1120. String token = st.nextToken();
  1121. int p = token.indexOf('=');
  1122. if (p != -1) {
  1123. disposition.put(token.substring(0, p).trim().toLowerCase(Locale.US), token.substring(p + 1).trim());
  1124. }
  1125. }
  1126. String pname = disposition.get("name");
  1127. pname = pname.substring(1, pname.length() - 1);
  1128.  
  1129. String value = "";
  1130. if (item.get("content-type") == null) {
  1131. while (mpline != null && !mpline.contains(boundary)) {
  1132. mpline = in.readLine();
  1133. if (mpline != null) {
  1134. int d = mpline.indexOf(boundary);
  1135. if (d == -1) {
  1136. value += mpline;
  1137. } else {
  1138. value += mpline.substring(0, d - 2);
  1139. }
  1140. }
  1141. }
  1142. } else {
  1143. if (boundarycount > bpositions.length) {
  1144. throw new ResponseException(Response.Status.INTERNAL_ERROR, "Error processing request");
  1145. }
  1146. int offset = stripMultipartHeaders(fbuf, bpositions[boundarycount - 2]);
  1147. //创建一个临时文件,然后保存内容,这个函数我们也需要重写setTempFileManagerFactory
  1148. String path = saveTmpFile(fbuf, offset, bpositions[boundarycount - 1] - offset - 4);
  1149. files.put(pname, path);
  1150. value = disposition.get("filename");
  1151. value = value.substring(1, value.length() - 1);
  1152. do {
  1153. mpline = in.readLine();
  1154. } while (mpline != null && !mpline.contains(boundary));
  1155. }
  1156. parms.put(pname, value);
  1157. }
  1158. }
  1159. } catch (IOException ioe) {
  1160. throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe);
  1161. }
  1162. }
  1163.  
  1164. /**
  1165. * Find byte index separating header from body. It must be the last byte of the first two sequential new lines.
  1166. * 找到head和body的分界点,两个回车换行
  1167. */
  1168. private int findHeaderEnd(final byte[] buf, int rlen) {
  1169. int splitbyte = 0;
  1170. while (splitbyte + 3 < rlen) {
  1171. if (buf[splitbyte] == '\r' && buf[splitbyte + 1] == '\n' && buf[splitbyte + 2] == '\r' && buf[splitbyte + 3] == '\n') {
  1172. return splitbyte + 4;
  1173. }
  1174. splitbyte++;
  1175. }
  1176. return 0;
  1177. }
  1178.  
  1179. /**
  1180. * Find the byte positions where multipart boundaries start.
  1181. * @param b
  1182. * @param boundary
  1183. * @return
  1184. */
  1185. private int[] getBoundaryPositions(ByteBuffer b, byte[] boundary) {
  1186. int matchcount = 0;
  1187. int matchbyte = -1;
  1188. List<Integer> matchbytes = new ArrayList<Integer>();
  1189. for (int i = 0; i < b.limit(); i++) {
  1190. if (b.get(i) == boundary[matchcount]) {
  1191. if (matchcount == 0)
  1192. matchbyte = i;
  1193. matchcount++;
  1194. if (matchcount == boundary.length) {
  1195. matchbytes.add(matchbyte);
  1196. matchcount = 0;
  1197. matchbyte = -1;
  1198. }
  1199. } else {
  1200. i -= matchcount;
  1201. matchcount = 0;
  1202. matchbyte = -1;
  1203. }
  1204. }
  1205. int[] ret = new int[matchbytes.size()];
  1206. for (int i = 0; i < ret.length; i++) {
  1207. ret[i] = matchbytes.get(i);
  1208. }
  1209. return ret;
  1210. }
  1211.  
  1212. /**
  1213. * Retrieves the content of a sent file and saves it to a temporary file. The full path to the saved file is returned.
  1214. */
  1215. private String saveTmpFile(ByteBuffer b, int offset, int len) {
  1216. String path = "";
  1217. if (len > 0) {
  1218. FileOutputStream fileOutputStream = null;
  1219. try {
  1220. //这个地方的tempFileManager需要我们setTempFileManagerFactory
  1221. TempFile tempFile = tempFileManager.createTempFile();
  1222. ByteBuffer src = b.duplicate();
  1223. fileOutputStream = new FileOutputStream(tempFile.getName());
  1224. FileChannel dest = fileOutputStream.getChannel();
  1225. src.position(offset).limit(offset + len);
  1226. dest.write(src.slice());
  1227. path = tempFile.getName();
  1228. } catch (Exception e) { // Catch exception if any
  1229. System.err.println("Error: " + e.getMessage());
  1230. } finally {
  1231. safeClose(fileOutputStream);
  1232. }
  1233. }
  1234. return path;
  1235. }
  1236.  
  1237. private RandomAccessFile getTmpBucket() {
  1238. try {
  1239. TempFile tempFile = tempFileManager.createTempFile();
  1240. return new RandomAccessFile(tempFile.getName(), "rw");
  1241. } catch (Exception e) {
  1242. System.err.println("Error: " + e.getMessage());
  1243. }
  1244. return null;
  1245. }
  1246.  
  1247. /**
  1248. * It returns the offset separating multipart file headers from the file's data.
  1249. */
  1250. private int stripMultipartHeaders(ByteBuffer b, int offset) {
  1251. int i;
  1252. for (i = offset; i < b.limit(); i++) {
  1253. if (b.get(i) == '\r' && b.get(++i) == '\n' && b.get(++i) == '\r' && b.get(++i) == '\n') {
  1254. break;
  1255. }
  1256. }
  1257. return i + 1;
  1258. }
  1259.  
  1260. /**
  1261. * Decodes parameters in percent-encoded URI-format ( e.g. "name=Jack%20Daniels&pass=Single%20Malt" ) and
  1262. * adds them to given Map. NOTE: this doesn't support multiple identical keys due to the simplicity of Map.
  1263. */
  1264. private void decodeParms(String parms, Map<String, String> p) {
  1265. if (parms == null) {
  1266. queryParameterString = "";
  1267. return;
  1268. }
  1269.  
  1270. queryParameterString = parms;
  1271. //使用&来分隔参数
  1272. StringTokenizer st = new StringTokenizer(parms, "&");
  1273. while (st.hasMoreTokens()) {
  1274. String e = st.nextToken();
  1275. int sep = e.indexOf('=');
  1276. if (sep >= 0) {
  1277. /*
  1278. * 这里使用decodePercent来解析,防止参数里面带有中文
  1279. * 比如“张杰”那么浏览器会写成%E5%BC%A0%E6%9D%B0
  1280. */
  1281. p.put(decodePercent(e.substring(0, sep)).trim(),
  1282. decodePercent(e.substring(sep + 1)));
  1283. } else {
  1284. p.put(decodePercent(e).trim(), "");
  1285. }
  1286. }
  1287. }
  1288.  
  1289. @Override
  1290. public final Map<String, String> getParms() {
  1291. return parms;
  1292. }
  1293.  
  1294. public String getQueryParameterString() {
  1295. return queryParameterString;
  1296. }
  1297.  
  1298. @Override
  1299. public final Map<String, String> getHeaders() {
  1300. return headers;
  1301. }
  1302.  
  1303. @Override
  1304. public final String getUri() {
  1305. return uri;
  1306. }
  1307.  
  1308. @Override
  1309. public final Method getMethod() {
  1310. return method;
  1311. }
  1312.  
  1313. @Override
  1314. public final InputStream getInputStream() {
  1315. return inputStream;
  1316. }
  1317.  
  1318. @Override
  1319. public CookieHandler getCookies() {
  1320. return cookies;
  1321. }
  1322. }
  1323.  
  1324. public static class Cookie {
  1325. private String n, v, e;
  1326.  
  1327. public Cookie(String name, String value, String expires) {
  1328. n = name;
  1329. v = value;
  1330. e = expires;
  1331. }
  1332.  
  1333. public Cookie(String name, String value) {
  1334. this(name, value, 30);
  1335. }
  1336.  
  1337. public Cookie(String name, String value, int numDays) {
  1338. n = name;
  1339. v = value;
  1340. e = getHTTPTime(numDays);
  1341. }
  1342.  
  1343. public String getHTTPHeader() {
  1344. String fmt = "%s=%s; expires=%s";
  1345. return String.format(fmt, n, v, e);
  1346. }
  1347.  
  1348. public static String getHTTPTime(int days) {
  1349. Calendar calendar = Calendar.getInstance();
  1350. SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
  1351. dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
  1352. calendar.add(Calendar.DAY_OF_MONTH, days);
  1353. return dateFormat.format(calendar.getTime());
  1354. }
  1355. }
  1356.  
  1357. /**
  1358. * Provides rudimentary support for cookies.
  1359. * Doesn't support 'path', 'secure' nor 'httpOnly'.
  1360. * Feel free to improve it and/or add unsupported features.
  1361. *
  1362. * @author LordFokas
  1363. */
  1364. public class CookieHandler implements Iterable<String> {
  1365. private HashMap<String, String> cookies = new HashMap<String, String>();
  1366. private ArrayList<Cookie> queue = new ArrayList<Cookie>();
  1367.  
  1368. public CookieHandler(Map<String, String> httpHeaders) {
  1369. String raw = httpHeaders.get("cookie");
  1370. if (raw != null) {
  1371. String[] tokens = raw.split(";");
  1372. for (String token : tokens) {
  1373. String[] data = token.trim().split("=");
  1374. if (data.length == 2) {
  1375. cookies.put(data[0], data[1]);
  1376. }
  1377. }
  1378. }
  1379. }
  1380.  
  1381. @Override public Iterator<String> iterator() {
  1382. return cookies.keySet().iterator();
  1383. }
  1384.  
  1385. /**
  1386. * Read a cookie from the HTTP Headers.
  1387. *
  1388. * @param name The cookie's name.
  1389. * @return The cookie's value if it exists, null otherwise.
  1390. */
  1391. public String read(String name) {
  1392. return cookies.get(name);
  1393. }
  1394.  
  1395. /**
  1396. * Sets a cookie.
  1397. *
  1398. * @param name The cookie's name.
  1399. * @param value The cookie's value.
  1400. * @param expires How many days until the cookie expires.
  1401. */
  1402. public void set(String name, String value, int expires) {
  1403. queue.add(new Cookie(name, value, Cookie.getHTTPTime(expires)));
  1404. }
  1405.  
  1406. public void set(Cookie cookie) {
  1407. queue.add(cookie);
  1408. }
  1409.  
  1410. /**
  1411. * Set a cookie with an expiration date from a month ago, effectively deleting it on the client side.
  1412. *
  1413. * @param name The cookie name.
  1414. */
  1415. public void delete(String name) {
  1416. set(name, "-delete-", -30);
  1417. }
  1418.  
  1419. /**
  1420. * Internally used by the webserver to add all queued cookies into the Response's HTTP Headers.
  1421. *
  1422. * @param response The Response object to which headers the queued cookies will be added.
  1423. */
  1424. public void unloadQueue(Response response) {
  1425. for (Cookie cookie : queue) {
  1426. response.addHeader("Set-Cookie", cookie.getHTTPHeader());
  1427. }
  1428. }
  1429. }
  1430. }

我们测试的时候需要自己定义的类:

  1. package com.sohu.nanohttpd;
  2.  
  3. import android.app.Activity;
  4. import android.os.Bundle;
  5. import android.util.Log;
  6.  
  7. public class MainActivity extends Activity {
  8.  
  9. @Override
  10. protected void onCreate(Bundle savedInstanceState) {
  11. super.onCreate(savedInstanceState);
  12. setContentView(R.layout.activity_main);
  13.  
  14. NanoHTTPD nanoHttpd = new MyNanoHTTPD("127.0.0.1",23456);
  15. try{
  16. nanoHttpd.start();
  17. }catch(Exception e){
  18. e.printStackTrace();
  19. }
  20.  
  21. Log.e("DEMO",nanoHttpd.isAlive()+"");
  22.  
  23. }
  24.  
  25. }
  26.  
  27. class MyNanoHTTPD extends NanoHTTPD{
  28.  
  29. public MyNanoHTTPD(int port) {
  30. super(port);
  31. }
  32.  
  33. public MyNanoHTTPD(String hostName,int port){
  34. super(hostName,port);
  35. }
  36.  
  37. public Response serve(IHTTPSession session) {
  38. Method method = session.getMethod();
  39. Log.e("DEMO","Method:"+method.toString());
  40. if(NanoHTTPD.Method.GET.equals(method)){
  41. //get方式
  42. String queryParams = session.getQueryParameterString();
  43. Log.e("DEMO","params:"+queryParams);
  44. }else if(NanoHTTPD.Method.POST.equals(method)){
  45. //post方式
  46. }
  47. return super.serve(session);
  48. }
  49.  
  50. }

这里只是做了一下拓展知识,两种方式搭建都可以的,但是明显Apache的功能强大一点。。

测试项目的下载地址:

Android测试项目HttpServer下载地址

http://download.csdn.net/detail/jiangwei0910410003/7432533

PC端的Server测试项目HttpServer下载地址

http://download.csdn.net/detail/jiangwei0910410003/7432537

Android测试项目NanoHTTPD下载地址

http://download.csdn.net/detail/jiangwei0910410003/7432595

总结:上面就是将PC端的Cookie和移动端的imei进行绑定的操作,这种操作的价值是很大的,未来如果用户在家里面进行上网的话,我们就可以将PC端和移动端进行紧密耦合在一起,相当于一个整体。。这样我们对用户的行为就更加了解了。。

Android中如何搭建一个WebServer的更多相关文章

  1. 在Android中动画移动一个View的位置,采用Scroller类实现Android动画之 View移动

    在Android中动画移动一个View的位置,采用Scroller类实现 今天说最近自己遇到的一个问题,就是要用动画效果来移动一个VIew的位置. 这个具体的情况是,需要做一个SlidingMenu的 ...

  2. Android中Service的一个Demo例子

    Android中Service的一个Demo例子  Service组件是Android系统重要的一部分,网上看了代码,很简单,但要想熟练使用还是需要Coding.  本文,主要贴代码,不对Servic ...

  3. Android在如何建立一个WebServer

    今天老板交待任务最终完成了,感觉收获颇多,所以写一个关于它的记录,首先,看一下.老板的需求 需求: 希望移动端的用户标识(IMEI)和HTML页面的用户标识(Cookie)连接起来,当中HTML页面可 ...

  4. Android中的第一个NDK的例子

    前几天研究了JNI技术后,想在Android上试一试研究结果,查阅了很多资料后,总结如下步骤: 首先来看一下什么是NDK NDK 提供了一系列的工具,帮助开发者快速开发C(或C++)的动态库,并能自动 ...

  5. 浅谈android中只使用一个TextView实现高仿京东,淘宝各种倒计时

    今天给大家带来的是只使用一个TextView实现一个高仿京东.淘宝.唯品会等各种电商APP的活动倒计时.近期公司一直加班也没来得及时间去整理,今天难得歇息想把这个分享给大家.只求共同学习,以及自己兴许 ...

  6. Android中自己定义一个shade.xml

    自己定义一个shade: <shape> <!-- 实心 --> <solid android:color="#ff9d77"/> <!- ...

  7. Android 中如何从一个App启动另外一个App(如启动支付界面、启动地图界面、应用商场下载App等场景)

    假定两个App,分别是A和B,当A运行某个功能需要启动B,一种是启动B应用,一种直接进入B的某个Activity.搜了很多资料,没有一个完整的.下面就A--Android5.1.1.B--Androi ...

  8. Android中调用另一个Activity并返回结果-以模拟选择头像功能为例

    场景 Android中点击按钮启动另一个Activity以及Activity之间传值: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/detail ...

  9. iOS 10中如何搭建一个语音转文字框架

    在2016WWDC大会上,Apple公司介绍了一个很好的语音识别的API,那就是Speech framework.事实上,这个Speech Kit就是Siri用来做语音识别的框架.如今已经有一些可用的 ...

随机推荐

  1. PHP rewinddir() 函数

    打开一个目录,列出其中的文件,充值目录句柄,重新列出其中的文件,然后关闭: <?php$dir = "/images/"; // Open a directory, and ...

  2. delphi 随意将函数执行权限提高到Ring0源代码

    //随意将函数执行权限提高到Ring0源代码//Windows 2K以上的操作系统,//用途: 提供超级简单使用的APIrocessRing0(),//可将delphi中的任意函数由原來的Ring3权 ...

  3. VC连接SQLite3的方法(MFC封装类)

    SQLite,是一款轻型的数据库,是遵守ACID的关联式数据库管理系统,支持跨平台,操作简单,能够使用很多语言直接创建数据库.官方网站:www.sqlite.org 在VC环境下编写连接SQLite的 ...

  4. [CSP-S模拟测试]:金(king)(高精度+模拟)

    题目传送门(内部题36) 输入格式 第一行一个整数$T$,表示数据组数. 接下来$T$行,每行两个空格隔开的整数$n,m$. 输出格式 对于每组数据,输出一行$"Yes"$或$&q ...

  5. JDK换版本问题解决

    在jdk安装第一个版本的时候,就默认在path配置值中加入C:\ProgramData\Oracle\Java\javapath; 所以我们需要把Path最前面的C:\ProgramData\Orac ...

  6. struts2 paramsPrepareParamsStack拦截器简化代码(源码分析)

    目录 一.在讲 paramsPrepareParamsStack 之前,先看一个增删改查的例子. 1. Dao.java准备数据和提供增删改查 2. Employee.java 为model 3. E ...

  7. CSS 设置鼠标显示形状

    CSS 设置鼠标显示形状 <style type="text/css"><!-- span {display:block;line-height:30px;mar ...

  8. 2017《Java学习》第二次作业 计科1502任秀兴

    学习git总结 安装git 1. 安装完成后执行命令git --version查看版本 2.执行命令git config --global user.nam "你的用户名",执行命 ...

  9. webservice 应用

    一直以来,dashboard就会面临一个非常难堪的问题.就是刷新速度太慢了.它要连接query 来获取数据.而query每刷一次都需要时间.这是无可避免的结果.尽管它也是结果集,可还是比较慢.最近实践 ...

  10. laravel新增路由文件

    除去原有路由文件,有时为方便路由管理,我们可以新增独立路由文件,如:针对管理后台的路由文件. 1.在routes文件夹下创建新路由文件admin.php 2.在app\Providers\RouteS ...