一、库简介
implementation 'com.koushikdutta.async:androidasync:2.2.1' // Http Server
源码github地址:https://github.com/koush/AndroidAsync
二、代码分享
1、HttpService.java(服务类)
package com.interjoy.utils.serviceutils;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
/**
* @author: cwang Interjoy
* @time: 2020/3/1114:55
* @Description:MyHttpServer的服务
*/
public class HttpService extends Service {
public HttpService(){
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
super.onCreate();
MyHttpServer.getInstance().start();
}
@Override
public void onDestroy() {
super.onDestroy();
MyHttpServer.getInstance().stop();
}
}
2、MyHttpServer.java(Http Server类)
package com.interjoy.utils.serviceutils;
import android.util.Log;
import com.interjoy.utils.systemutils.AccessInfo;
import com.koushikdutta.async.http.body.AsyncHttpRequestBody;
import com.koushikdutta.async.http.server.AsyncHttpServer;
import com.koushikdutta.async.http.server.AsyncHttpServerRequest;
import com.koushikdutta.async.http.server.AsyncHttpServerResponse;
import com.koushikdutta.async.http.server.HttpServerRequestCallback;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @author: cwang
* @time: 2020/3/11 15:01
* @Description:HttpServer
*/
public class MyHttpServer implements HttpServerRequestCallback {
private static final String TAG = "MyHttpServer";
private static MyHttpServer mInstance;
private static int PORT_DEFALT = 12020; // 监听端口号
private static String ERRORCODE = "error_code"; // error_code
private static String ERRORMSG = "error_msg"; // error_msg
private static String COMPANYKEY = "cwang.com"; // 公司Key
private static String SECRET = "xxxxx"; // 秘钥
AsyncHttpServer mServer = new AsyncHttpServer();
public static MyHttpServer getInstance() {
if (mInstance == null) {
synchronized (MyHttpServer.class) {
if (mInstance == null) {
mInstance = new MyHttpServer();
}
}
}
return mInstance;
}
/**
* 开始监听端口
*/
public void start() {
Log.d(TAG, "Starting http server...");
mServer.get("[\\d\\D]*", this);
mServer.post("[\\d\\D]*", this);
mServer.listen(PORT_DEFALT);
}
/**
* 停止监听端口
*/
public void stop() {
Log.d(TAG, "Stopping http server...");
mServer.stop();
}
/**
* 发送响应信息给Client端
*
* @param response
* @param json
*/
private void sendResponse(AsyncHttpServerResponse response, JSONObject json) {
// Enable CORS
response.getHeaders().add("Access-Control-Allow-Origin", "*");
response.send(json);
}
@Override
public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
String uri = request.getPath();
Log.d(TAG, "onRequest " + uri);
Object params = null;
if (request.getMethod().equals("POST")) {
String contentType = request.getHeaders().get("Content-Type"); // Content-Type
String authorization = request.getHeaders().get("Authorization"); // 鉴权串
Log.i(TAG, "authorization == " + authorization);
// 验证Content-Type
if (!contentType.equals("application/json")) {
Log.e(TAG, "Headers Content-Type Error");
handleInvalidContentTypeRequest(params, response);
return;
}
// 验证鉴权
int keyIndex = authorization.indexOf(COMPANYKEY); // 公司key下标
if (keyIndex <= 0) { // 截取出明文、SHA256串
Log.e(TAG, "Headers Authorization Error");
handleInvalidAuthorizationRequest(params, response);
return;
}
String plainTextSignatureStr = authorization.substring(keyIndex);
Log.i(TAG, "plainTextSignatureStr == " + plainTextSignatureStr);
String sha256 = authorization.substring(0, keyIndex);
Log.i(TAG, "sha256 == " + sha256);
String key_signatureStr = SECRET + plainTextSignatureStr; // 秘钥+明文
Log.i(TAG, "key_signatureStr 明文== " + key_signatureStr);
String shaStr = new SHA256Encrypt().bin2hex(key_signatureStr); // SHA256算法加密
Log.i(TAG, "mAuthorization sha == " + shaStr);
if (!sha256.equals(shaStr)) { // 授权失败
Log.e(TAG, "Headers Authorization Error");
handleInvalidAuthorizationRequest(params, response);
return;
}
params = ((AsyncHttpRequestBody) request.getBody()).get();
} else {
Log.e(TAG, "Unsupported RequestProtocol");
handleInvalidUnsupportedRequestProtocolRequest(params, response);
return;
}
if (params != null) {
Log.d(TAG, "params = " + params.toString());
}
// 解析API
switch (uri) {
case "/getDeviceInfo": // 获取设备信息
handleDeviceInfoRequest(params, response);
break;
default: // 无效API请求
handleInvalidRequest(params, response);
break;
}
}
/**
* 获取设备信息
*
* @param params 请求参数
* @param response
*/
private void handleDeviceInfoRequest(Object params, AsyncHttpServerResponse response) {
// Send JSON format response
try {
JSONObject json = new JSONObject();
json.put("SystemModel", AccessInfo.getSystemModel());
json.put("DeviceSN", AccessInfo.getDeviceSN());
json.put("DeviceName", AccessInfo.getDeviceName());
json.put("SystemVersion", AccessInfo.getSystemVersion());
json.put("SoftVersion", AccessInfo.getSoftVersion());
sendResponse(response, json);
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* 无效请求
*
* @param params
* @param response
*/
private void handleInvalidRequest(Object params, AsyncHttpServerResponse response) {
JSONObject json = new JSONObject();
try {
json.put("error", "InvalidAPI");
sendResponse(response, json);
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* 请求的Content-Type不对
*
* @param params
* @param response
*/
private void handleInvalidContentTypeRequest(Object params, AsyncHttpServerResponse response) {
JSONObject json = new JSONObject();
try {
json.put("error", "ContentType");
sendResponse(response, json);
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* 请求的Authorization不对
*
* @param params
* @param response
*/
private void handleInvalidAuthorizationRequest(Object params, AsyncHttpServerResponse response) {
JSONObject json = new JSONObject();
try {
json.put("error", "Authorization");
sendResponse(response, json);
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* 请求协议不对
*
* @param params
* @param response
*/
private void handleInvalidUnsupportedRequestProtocolRequest(Object params, AsyncHttpServerResponse response) {
JSONObject json = new JSONObject();
try {
json.put("error", "UnsupportedRequestProtocol");
sendResponse(response, json);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
3、AndroidManifest.xml(注册服务)