码迷,mamicode.com
首页 > 移动开发 > 详细

用自己的Android手机做迷你短信机

时间:2014-11-05 23:19:53      阅读:624      评论:0      收藏:0      [点我收藏+]

标签:android   webservice   短信   短信机   服务器   

1、Android httpserver 和 http调试

Android http server  : httpcore

PC http client  : httpdebug


2、短信发送

Android自带的android.telephony.SmsManager包


3、源码:


package com.example.httpservertest;


import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.Locale;


import org.apache.http.ConnectionClosedException;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpServerConnection;
import org.apache.http.HttpStatus;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.DefaultHttpServerConnection;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpRequestHandlerRegistry;
import org.apache.http.protocol.HttpService;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.ResponseConnControl;
import org.apache.http.protocol.ResponseContent;
import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer;

import android.telephony.SmsManager;

/**
 * Basic, yet fully functional and spec compliant, HTTP/1.1 file server.
 * <p>
 * Please note the purpose of this application is demonstrate the usage of
 * HttpCore APIs. It is NOT intended to demonstrate the most efficient way of
 * building an HTTP file server.
 * 
 * 
 */
public class HttpServer {


	public static void start(String[] args) throws Exception {


		Thread t = new RequestListenerThread(8080);
		t.setDaemon(false);
		t.start();		//start the webservice server
	}

	static class WebServiceHandler implements HttpRequestHandler {


		public WebServiceHandler() {
			super();
		}


		public void handle(final HttpRequest request,
				final HttpResponse response, final HttpContext context)
				throws HttpException, IOException {			


			String method = request.getRequestLine().getMethod()
					.toUpperCase(Locale.ENGLISH);
			//get uri
			String target = request.getRequestLine().getUri();
		        
			//解析手机号、随机码
			String mobile = "86"+target.substring(target.indexOf("mobile")+7,target.indexOf("&"));
			String regcode = target.substring(target.indexOf("regcode")+8);
			System.out.println("mobile " + mobile + "regcode " + regcode);
			

			// send sms
			String content = "【CSDN-lonelyrains】您的注册验证码为:" + regcode;
			
			SmsManager smsManager = SmsManager.getDefault();
			
			List<String> texts = smsManager.divideMessage(content);
			
			for(String text:texts)
			{
				smsManager.sendTextMessage(mobile,  null, text, null, null);
			}
			
			if (method.equals("GET") ) {
				System.out.println("GET " + target);
				response.setStatusCode(HttpStatus.SC_OK);
				StringEntity entity = new StringEntity("<xml><method>get</method><url>" + target + "</url></xml>");
				response.setEntity(entity);
			}
			else if (method.equals("POST") )
			{
				System.out.println("POST " + target);
				response.setStatusCode(HttpStatus.SC_OK);
				StringEntity entity = new StringEntity("<xml><method>post</method><url>" + target + "</url></xml>");
				response.setEntity(entity);
			}
			else
			{
				throw new MethodNotSupportedException(method
						+ " method not supported");
			}
			
		}


	}


	static class RequestListenerThread extends Thread {


		private final ServerSocket serversocket;
		private final HttpParams params;
		private final HttpService httpService;


		public RequestListenerThread(int port)
				throws IOException {
			// 
			this.serversocket = new ServerSocket(port);

			System.out.println("RequestListenerThread start");
			
			// Set up the HTTP protocol processor
			HttpProcessor httpproc = new ImmutableHttpProcessor(
					new HttpResponseInterceptor[] {
							new ResponseDate(), new ResponseServer(),
							new ResponseContent(), new ResponseConnControl() });


			this.params = new BasicHttpParams();
			this.params
					.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
					.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE,
							8 * 1024)
					.setBooleanParameter(
							CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
					.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
					.setParameter(CoreProtocolPNames.ORIGIN_SERVER,
							"HttpComponents/1.1");


			// Set up request handlers
			HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
			reqistry.register("*", new WebServiceHandler());  //WebServiceHandler用来处理webservice请求。


			this.httpService = new HttpService(httpproc,
					new DefaultConnectionReuseStrategy(),
					new DefaultHttpResponseFactory());
			httpService.setParams(this.params);
			httpService.setHandlerResolver(reqistry);		//为http服务设置注册好的请求处理器。


		}


		@Override
		public void run() {
			System.out.println("Listening on port "
					+ this.serversocket.getLocalPort());
			System.out.println("Thread.interrupted = " + Thread.interrupted()); 
			while (!Thread.interrupted()) {
				try {
					// Set up HTTP connection
					Socket socket = this.serversocket.accept();
					DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
					System.out.println("Incoming connection from "
							+ socket.getInetAddress());
					conn.bind(socket, this.params);


					// Start worker thread
					Thread t = new WorkerThread(this.httpService, conn);
					t.setDaemon(true);
					t.start();
				} catch (InterruptedIOException ex) {
					break;
				} catch (IOException e) {
					System.err
							.println("I/O error initialising connection thread: "
									+ e.getMessage());
					break;
				}
			}
		}
	}


	static class WorkerThread extends Thread {


		private final HttpService httpservice;
		private final HttpServerConnection conn;


		public WorkerThread(final HttpService httpservice,
				final HttpServerConnection conn) {
			super();
			this.httpservice = httpservice;
			this.conn = conn;
		}


		@Override
		public void run() {
			System.out.println("New connection thread");
			HttpContext context = new BasicHttpContext(null);
			try {
				while (!Thread.interrupted() && this.conn.isOpen()) {
					this.httpservice.handleRequest(this.conn, context);
				}
			} catch (ConnectionClosedException ex) {
				System.err.println("Client closed connection");
			} catch (IOException ex) {
				System.err.println("I/O error: " + ex.getMessage());
			} catch (HttpException ex) {
				System.err.println("Unrecoverable HTTP protocol violation: "
						+ ex.getMessage());
			} finally {
				try {
					this.conn.shutdown();
				} catch (IOException ignore) {
				}
			}
		}
	}
}

4、配置: 

    在AndroidManifest.xml里添加权限:

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.SEND_SMS" />

5、调用:  在activity里调用Httpserver.start(null)就可以启动了


6、测试:  httpdebug  发送测试示例: http://192.168.1.101:8080/?mobile=12312341234&regcode=232423


7、遇到的问题:

1)笔记本和wifi同时使用无线网时,发现路由器禁用了无线网设备互相通信的功能,这个开启AP隔离的配置需要去掉打钩:

bubuko.com,布布扣

2)某派大神F1手机调用httpcore作为httpserver,运行时报错:Library ‘libmaliinstr.so‘ not found。发现有人用这手机做别的也报这个错,换一台手机后正常。看名字应该是Arm的Mali图形硬件的相关库



参考链接

http://blog.csdn.net/jkeven/article/details/9271145

用自己的Android手机做迷你短信机

标签:android   webservice   短信   短信机   服务器   

原文地址:http://blog.csdn.net/lonelyrains/article/details/40711345

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!