public class HttpService extends NanoHTTPD {
final String SEARCH_IMAGE = "/getImageFrame";
final String SEARCH_IMAGE_INPUT_STREAM = "/getImageStream";
public HttpService(int port) {
super(port);
}
@Override
public Response serve(IHTTPSession session) {
String response = "";
Log.e("收到的请求", session.getUri());
if (session.getMethod() == Method.GET) {
if(TextUtils.equals(session.getUri(),SEARCH_IMAGE_INPUT_STREAM)){
try{
FileInputStream fis = null;
File file = new File("");
if (file.exists()){
fis = new FileInputStream(file);
Log.d("", "File exists: " + file.getAbsolutePath());
} else {
Log.d("", "File doesn't exist!");
}
return Response.newChunkedResponse(Status.OK, "image/jpeg", fis);
}catch (Exception e){
e.printStackTrace();
}
}
response = doGetRequest(session);
}
Log.e("返回结果", response);
return Response.newFixedLengthResponse(Status.OK, "application/json;charset=UTF-8", response);
}
public void startServer() {
try {
this.start();
Log.e("HttpService", "start");
} catch (IOException e) {
e.printStackTrace();
Log.e("HttpService", "start fail");
}
}
public void stopServer() {
this.stop();
Log.e("HttpService", "stop");
}
public String doGetRequest(IHTTPSession session) {
switch (session.getUri()) {
case SEARCH_IMAGE:
return getImage(session);
default:
break;
}
return "";
}
private String getImage(IHTTPSession session) {
JSONObject object = new JSONObject();
try {
object.put("code", 0);
object.put("msg", "成功");
object.put("data", MyApplication.getApplication().getMCurrentImageFrameBase64().getValue());
} catch (JSONException e) {
e.printStackTrace();
}
return object.toString();
}
public Map<String, String> getGetParam(String str) {
Map<String, String> map = new HashMap<>();
if (TextUtils.isEmpty(str)) {
return map;
}
String[] agrs = str.split("&");
for (String it : agrs) {
String[] s = it.split("=");
map.put(s[0], s[1]);
}
return map;
}
}