本文整理匯總了Java中fi.iki.elonen.NanoHTTPD類的典型用法代碼示例。如果您正苦於以下問題:Java NanoHTTPD類的具體用法?Java NanoHTTPD怎麽用?Java NanoHTTPD使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
NanoHTTPD類屬於fi.iki.elonen包,在下文中一共展示了NanoHTTPD類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: executeInstance
import fi.iki.elonen.NanoHTTPD; //導入依賴的package包/類
public static void executeInstance(NanoHTTPD server) {
try {
server.start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
} catch (IOException ioe) {
System.err.println("Couldn't start server:\n" + ioe);
System.exit(-1);
}
System.out.println("Server started, Hit Enter to stop.\n");
try {
System.in.read();
} catch (Throwable ignored) {
}
server.stop();
System.out.println("Server stopped.\n");
}
示例2: startServer
import fi.iki.elonen.NanoHTTPD; //導入依賴的package包/類
/**
* Start the caching tiles server
* @return TRUE when server is available
*/
public boolean startServer(){
final String tag="startServer - ";
boolean result=false;
if (!running){
final int cleanup = cleanupOldFiles();
Log.i(TAG, tag + "Deleted: " + cleanup + " files from caching tile server.");
try {
start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
Log.i(TAG,tag+"Running! Point your browser to http://localhost:8181/ \n");
} catch (IOException e) {
Log.e(TAG,tag, e);
}
running=true;
result=true;
} else {
result=true;
}
return result;
}
示例3: handleSessionInput
import fi.iki.elonen.NanoHTTPD; //導入依賴的package包/類
private void handleSessionInput(NanoHTTPD.IHTTPSession session) {
if (notificationHandlers.containsKey(session.getUri())) {
NotificationHandler notificationHandler = notificationHandlers.get(session.getUri());
String lengthHeader = session.getHeaders().getOrDefault("content-length", null);
int contentLength = NumberConverter.asNumber(lengthHeader).withDefault(0).toInteger();
byte[] buffer = new byte[contentLength];
try {
session.getInputStream().read(buffer, 0, contentLength);
String data = new String(buffer).trim();
if (StringUtils.isNotEmpty(data)) {
WebhookNotification notification = notificationHandler.unmarshalNotification(data);
if (!this.notificationIdHistory.contains(notification.getId())) {
logger.debug("New notification on topic: " + notification.getTopic());
this.notificationIdHistory.add(notification.getId(), 1, TimeUnit.HOURS);
//noinspection unchecked Unchecked error can never occur, since the notification is unmarshalled by the handler
notificationHandler.handleNotification(eventBus, notification);
}
}
} catch (IOException e) {
logger.error("Failed reading input", e);
}
}
}
示例4: doGet
import fi.iki.elonen.NanoHTTPD; //導入依賴的package包/類
public Response doGet(IHTTPSession session) {
String uri = session.getUri();
String path = uri.substring(getRequestMappingURL().length());
File result = new File(basePath, path);
String requestCanonicalPath;
try {
requestCanonicalPath = result.getCanonicalPath();
} catch (IOException e1) {
return new503ErrorResponse();
}
//prevent escape from configured base directory
if (!requestCanonicalPath.startsWith(canonicalBasePath) || !result.exists()) {
return NanoHTTPD.newFixedLengthResponse(fi.iki.elonen.NanoHTTPD.Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "not found");
}
try {
return NanoHTTPD.newFixedLengthResponse(fi.iki.elonen.NanoHTTPD.Response.Status.OK, getMimeType(uri), new FileInputStream(result), result.length());
} catch (FileNotFoundException e) {
return new503ErrorResponse();
}
}
示例5: get
import fi.iki.elonen.NanoHTTPD; //導入依賴的package包/類
@Override
public NanoHTTPD.Response get(RouterNanoHTTPD.UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) {
String sessionId = urlParams.get("sessionId");
Map<String, String> body = new HashMap<String, String>();
UiDevice mDevice = Elements.getGlobal().getmDevice();
JSONObject result = null;
try {
session.parseBody(body);
String postData = body.get("postData");
JSONObject jsonObj = JSON.parseObject(postData);
JSONArray keycodes = (JSONArray)jsonObj.get("value");
for (Iterator iterator = keycodes.iterator(); iterator.hasNext();) {
int keycode = (int) iterator.next();
mDevice.pressKeyCode(keycode);
}
return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(result, sessionId).toString());
} catch (Exception e) {
return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(Status.UnknownError, sessionId).toString());
}
}
示例6: get
import fi.iki.elonen.NanoHTTPD; //導入依賴的package包/類
@Override
public Response get(UriResource uriResource, Map<String, String> urlParams, IHTTPSession session) {
Method method = session.getMethod();
String uri = session.getUri();
//Log.d(TAG, "Method: " + method + ", Url: " + uri);
try {
EpubFetcher fetcher = uriResource.initParameter(EpubFetcher.class);
int offset = uri.indexOf("/", 0);
int startIndex = uri.indexOf("/", offset + 1);
String filePath = uri.substring(startIndex + 1);
Link link = fetcher.publication.getResourceMimeType(filePath);
String mimeType = link.getTypeLink();
InputStream inputStream = fetcher.getDataInputStream(filePath);
response = serveResponse(session, inputStream, mimeType);
} catch (EpubFetcherException e) {
e.printStackTrace();
return NanoHTTPD.newFixedLengthResponse(Status.INTERNAL_ERROR, getMimeType(), ResponseStatus.FAILURE_RESPONSE);
}
return response;
}
示例7: serve
import fi.iki.elonen.NanoHTTPD; //導入依賴的package包/類
/**
* Handle the HTML request.
*/
@Override
public Response serve(IHTTPSession session) {
NanoHTTPD.Response ws = mResponseHandler.serve(session);
if (ws == null) {
String uri = session.getUri();
try {
switch (uri) {
case "/":
return getHTMLResponse("home.html");
case "/css/style.css":
InputStream inputStream = mAssetManager.open("css/style.css");
return new NanoHTTPD.Response(Response.Status.OK, "text/css", inputStream);
case "/script/script.js":
inputStream = mAssetManager.open("script/script.js");
return new NanoHTTPD.Response(Response.Status.OK, "text/javascript", inputStream);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return ws;
}
示例8: serve
import fi.iki.elonen.NanoHTTPD; //導入依賴的package包/類
@Override
public Response serve(IHTTPSession session) {
Response response;
String uri = session.getUri();
if (uri.equals("/")){
uri = "/index.html";
}
String mimetype = getMimeType(uri);
Log.d("HTTPServer","MimeType: "+mimetype);
if (mimetype != null) {
//Handle text files
if (mimetype.contains("text/") || mimetype.contains("image/")){
response = newFixedLengthResponse(getTextFile(uri.substring(1)));
} else { //handle binary files
FileInputStream fcontent = getBinaryFile(uri.substring(1));
response = NanoHTTPD.newChunkedResponse(Response.Status.OK,mimetype,fcontent);
}
response.setMimeType(mimetype);
} else { //Let API Object handle the request
response = newFixedLengthResponse(mAPI.handle(session));
response.setMimeType("application/json");
}
//Allow CORS
response.addHeader("Access-Control-Allow-Origin","*");
response.addHeader("Access-Control-Allow-Headers","auth-user, auth-password");
return response;
}
示例9: get
import fi.iki.elonen.NanoHTTPD; //導入依賴的package包/類
@Override
public NanoHTTPD.Response get(RouterNanoHTTPD.UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) {
String sessionId = urlParams.get("sessionId");
String elementId = urlParams.get("elementId");
try {
Element el = Elements.getGlobal().getElement(elementId);
JSONObject props = new JSONObject();
props.put("text", el.element.getText());
props.put("description", el.element.getContentDescription());
props.put("enabled", el.element.isEnabled());
props.put("checkable", el.element.isCheckable());
props.put("checked", el.element.isChecked());
props.put("clickable", el.element.isClickable());
props.put("focusable", el.element.isFocusable());
props.put("focused", el.element.isFocused());
props.put("longClickable", el.element.isLongClickable());
props.put("scrollable", el.element.isScrollable());
props.put("selected", el.element.isSelected());
return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(props, sessionId).toString());
} catch (final Exception e) {
return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(Status.UnknownError, sessionId).toString());
}
}
示例10: get
import fi.iki.elonen.NanoHTTPD; //導入依賴的package包/類
@Override
public NanoHTTPD.Response get(RouterNanoHTTPD.UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) {
String sessionId = urlParams.get("sessionId");
try {
UiDevice mDevice = Elements.getGlobal().getmDevice();
Integer width = mDevice.getDisplayWidth();
Integer height = mDevice.getDisplayHeight();
JSONObject size = new JSONObject();
size.put("width", width);
size.put("height", height);
return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(size, sessionId).toString());
} catch(Exception e) {
return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(Status.UnknownError, sessionId).toString());
}
}
示例11: get
import fi.iki.elonen.NanoHTTPD; //導入依賴的package包/類
@Override
public NanoHTTPD.Response get(RouterNanoHTTPD.UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) {
String sessionId = urlParams.get("sessionId");
JSONObject result = null;
try {
acceptAlert();
return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(result, sessionId).toString());
} catch (final Exception e) {
return NanoHTTPD.newFixedLengthResponse(getStatus(), getMimeType(), new Response(Status.UnknownError, sessionId).toString());
}
}
示例12: isRequestFile
import fi.iki.elonen.NanoHTTPD; //導入依賴的package包/類
/**
* 判斷請求是否是下載文件
* @param session
* @return
*/
public static boolean isRequestFile(NanoHTTPD.IHTTPSession session){
String uri = session.getUri(); // 獲取請求連接,範例:/xxx/yyy/zz.doc
String ext = getExt(uri);
if(ext == null){
return false;
}
if(NanoHTTPD.mimeTypes().containsKey(ext)){
return true;
}
return false;
}
示例13: run
import fi.iki.elonen.NanoHTTPD; //導入依賴的package包/類
public static <T extends NanoHTTPD> void run(Class<T> serverClass) {
try {
executeInstance(serverClass.newInstance());
} catch (Exception e) {
ServerRunner.LOG.log(Level.SEVERE, "Cound nor create server", e);
}
}
示例14: serve
import fi.iki.elonen.NanoHTTPD; //導入依賴的package包/類
@Override
public Response serve(IHTTPSession session) {
final String tag = "serve - ";
Response res = null;
requestCount++;
final String url = "http:/" + session.getUri(); // URI starts with /
if (isAllowed(url)) {
final File imageFile = getImage(url);
if (imageFile!=null && imageFile.exists()){
try {
res = newFixedLengthResponse(Response.Status.OK, "image/png", new FileInputStream(imageFile), (int) imageFile.length());
res.addHeader("Accept-Ranges", "bytes");
res.addHeader("Access-Control-Allow-Methods", "DELETE, GET, POST, PUT");
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Headers", "X-Requested-With");
} catch (FileNotFoundException e) {
Log.e(TAG, tag, e);
}
} else {
Log.e(TAG, tag + "Image file does not exist ("+imageFile+").");
}
} else {
Log.e(TAG, tag + "URL is not allowed.");
}
if (res==null){
notFoundCount++;
res=newFixedLengthResponse(Response.Status.NOT_FOUND,NanoHTTPD.MIME_PLAINTEXT,"Error 404, file not found.");
}
return res;
}
示例15: enableHTTPS
import fi.iki.elonen.NanoHTTPD; //導入依賴的package包/類
private void enableHTTPS() {
try {
LocalRepoKeyStore localRepoKeyStore = LocalRepoKeyStore.get(context);
SSLServerSocketFactory factory = NanoHTTPD.makeSSLSocketFactory(
localRepoKeyStore.getKeyStore(),
localRepoKeyStore.getKeyManagers());
makeSecure(factory);
} catch (LocalRepoKeyStore.InitException | IOException e) {
Log.e(TAG, "Could not enable HTTPS", e);
}
}